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()?


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:

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

    echo 'Post Object AFTER update:';

    echo 'Post Object BEFORE update:';

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

  • The codex says use this hook whenever you need to compare values before and after the post update. – busyjax Jul 1 '17 at 21:49
  • Yes, it's main function is for that, but nothing stops you to use for your purpose. – Cesar Henrique Damascena Jul 1 '17 at 22:11
  • Can you show me a dummy code using this hook? – busyjax Jul 1 '17 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 – Cesar Henrique Damascena Jul 2 '17 at 0:45
  • No, I am asking where do I need to define my function B. – busyjax Jul 2 '17 at 11:56

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' );
  • It is working in both cases. – busyjax Jul 2 '17 at 16:02

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.