0

I have a couple of actions setup:

add_action('publish_post', array($this, 'newPost'), 10, 2); 
add_action('post_updated', array($this, 'updatePost'), 10, 3);

When I update an already published post the 'newPost' method is fired as opposed to the 'updatePost' method. I imagine this is because the post is already published so what would be a good way to fire a different method (or be able to identify that it's an update as opposed to a newly published post) when a previously published post is updated?

3 Answers 3

2

As an alternative, you can make use of the 'transition_post_status' hook for this. This hook is fired whenever a post's status is changed. In your case, you need to check whether the old and new status of the post is the same, which is publish

You can also set conditionals according to $post, which is the current post being updated/published etc.

You can try the following:

add_action('transition_post_status', function ($new_status, $old_status, $post) {

   if ( $old_status == 'publish' && $new_status == 'publish' ) {
       //Do something when post is updated
   }

}, 10, 3 );
1

You can use post status transition actions for this.

function wpd_updating_a_published_post( $post ){
    // do something
}
add_action( 'publish_to_publish', 'wpd_updating_a_published_post', 10, 1 );
2
  • Milo: This seems like a very concise way to do it. The only problem is that my 'publish_page' and 'publish_post' actions get fired as well. How can I check in those methods if the page/post is an existing one?
    – niczak
    Jan 8, 2015 at 19:27
  • Never mind, I got it!
    – niczak
    Jan 8, 2015 at 22:22
1

You can user Milo 's answer or you can use the conditional inside the hooked function, and then compare the post_date and the post_modified.

add_action('save_post', array($this, 'updatePost'), 10, 3);

function updatePost($post_id){

// If this is just a revision, don't send the email.
if ( wp_is_post_revision( $post_id ) )
    return;

$post = get_post($post_id);

// Compare the date
if ($post->post_date == $post->post_modified){
    // Do something for a new post

} elseif ($post->post_date < $post->post_modified){
    // Do something for an updated post
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.