0

I am trying to add some code to be run when a post is updated. To get started I have added the following code to my functions.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 );

However, it doesn't seem to work. Nothing has changed when updating a post - nothing is echoed or dumped on screen.

Did I misunderstand something?

3
  • What is not working?
    – bravokeyl
    Aug 9, 2016 at 7:25
  • I guess it is supposed to show the echoes and var_dumps on screen as I update a post? It doesnt do that :-) Aug 9, 2016 at 7:26
  • Try writing logs. Sometimes due to the theme or any other reason data won't echo using var_dump. Apr 19 at 7:43

1 Answer 1

0

If it doesn't work you can try to use a wp_insert_post action:

function insert_post_hook($post_id, $post) {

    if ($post->post_date != $post->post_modified) {
        // This post is being updated!
    }
    else {
        // This post is being created!
    }
}
add_action( 'wp_insert_post', 'insert_post_hook', 10, 2 );

If you want to see the latest version you could enable revisions:

define('WP_POST_REVISIONS', 3 ); 

This will save a maximum of 3 revisions.

After enabling you can check the following:

$latest_revision = array_shift(wp_get_post_revisions($post->ID));
6
  • What I need to do, is to compare the old content of the post with the new content. I am adding notifications for things that has changed. That's why I wanted to use post_updated with $post_before. Can I do something similar with wp_insert_post? Aug 9, 2016 at 7:35
  • I think this can only be done with revisions, see modified answer.
    – Paul
    Aug 9, 2016 at 7:39
  • Thanks. But shouldn't the following approach echo on screen when saving a post? It doesn't do that either.. function insert_post_hook($post_id, $post) { echo 'The post was saved'; } add_action( 'wp_insert_post', 'insert_post_hook', 10, 2 ); Aug 9, 2016 at 7:41
  • 1
    You should probably add a exit; afterwards.
    – Paul
    Aug 9, 2016 at 7:42
  • Okay. I managed to get my post_revisions. However, the $latest_revision only contains the title, time and some more basic stuff. It doesnt contain all the fields that are shown in revisions in the editor. Can I get it all somehow? Aug 9, 2016 at 8:17

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.