Wordpress hooks after a post is saved

2020-08-05 10:46发布

问题:

I have been searching and found a lot of various answers, however, I have not found a definitive answer.

I need to run a function right after a post is done saving to the database. This includes every aspect of the post including post metas. I have tried to hook into save_post but that seems to run my function before post metas are saved. I have also tried post_updated and updated_postmeta, but my function doesn't seem to run on either of them.

Another thing to note, I need to have access to the post ID inside my function.

Edit, My plugin uses the Advanced Custom Fields plugin and the function I have coded uses update_field to either create new post metas or update existing one based on some stuff. This code works. When I run the function at the post_updated hook the function seems to run but nothing happens. If I add die() to the end of my function my code works, but die kills the page and all I am left with is a blank white page at the url wp-admin/post.php. So adding die allows my function to work and I am not sure why it would not work without die.

回答1:

I would comment your post, but I cannot because I dont have 50 rep.

Do you mean the_post? https://codex.wordpress.org/Plugin_API/Action_Reference/the_post

function my_the_post_action( $post_object ) {
    // modify post object here
}
add_action( 'the_post', 'my_the_post_action' );

it ought to have the post Id

https://developer.wordpress.org/reference/hooks/the_post/



回答2:

Okay I found how to make publish_post work.

For custom post type you need to replace the "post" by the post type slug.

Example with the custom post type "Recipe" with "recipe" slug.

add_action('publish_recipe', 'test_publish_post', 10, 2);
function test_publish_post($post_id, $post){

    wp_die($post_id);
}

Don't forget to wp_die() or die(); else you will be redirected and you won't see your var_dump();



回答3:

I was able to fix my issue. It turns out that save_post does seem to run after post metas are saved. My problem actually came from something else inside my code that I was able to fix by changing how I handled that part of my script.



标签: php wordpress