1

I want to run a function A() when a post is published and function B() when the same post is edited or updated.

For this, I found publish_post action which is triggered whenever a post is published, or if it is edited and the status is changed to publish.

How can I use this publish_post action to know that post has been edited or updated so that I can run function B()?

2 Answers 2

2

With the post_updated hook you can trigger an action when the post is updated. He passes 3 parameters:

  • $post_ID (the post ID),
  • $post_after(the post object after the edit),
  • $post_before (the post object before the edit)

Here's an example:

<?php
function check_values($post_ID, $post_after, $post_before){
    echo 'Post ID:';
    var_dump($post_ID);

    echo 'Post Object AFTER update:';
    var_dump($post_after);

    echo 'Post Object BEFORE update:';
    var_dump($post_before);
}

add_action( 'post_updated', 'check_values', 10, 3 ); //don't forget the last argument to allow all three arguments of the function
?>

See reference Codex

8
  • The codex says use this hook whenever you need to compare values before and after the post update.
    – busyjax
    Jul 1, 2017 at 21:49
  • Yes, it's main function is for that, but nothing stops you to use for your purpose. Jul 1, 2017 at 22:11
  • Can you show me a dummy code using this hook?
    – busyjax
    Jul 1, 2017 at 22:39
  • @busyjax Sure, the code in my answer works.. just put that in your functions.php and you will see that the var_dumps will show the content of the posts, including the $post_id that you're trying to get Jul 2, 2017 at 0:45
  • No, I am asking where do I need to define my function B.
    – busyjax
    Jul 2, 2017 at 11:56
1

You could achieve this with save_post hook.

Example similar to code in codex

function run_my_function( $post_id ) {
  if ( wp_is_post_revision( $post_id ) ){
    // if post udpated
  } else {
    //if is new post
    }
}
add_action( 'save_post', 'run_my_function' );
4
  • It is working in both cases.
    – busyjax
    Jul 2, 2017 at 16:02
  • $post_id where does it come from Mar 3, 2021 at 9:43
  • In BenB's answer? It's passed into the function by the code that calls the save_post filter.
    – Rup
    Mar 3, 2021 at 10:40
  • @MehmetCemil don't post comments as solutions, even if you don't have the reputation to post comments. You'll get banned by the automation as a spammer. I recommend reading about hooks/actions/filters
    – Tom J Nowell
    Mar 3, 2021 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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