0

Can we talk about WordPress revision? How do I save the metadata revision of a WordPress Custom Post Type?

I have searched for it for endless hours today and other days, I have found one decent article about it that I will cite it below. I believe this could be helpful to many, mainly because there is not much out there that talks about this feature and how to save revisions of a meta data field. WordPress revision feature seems to be left behind sometime ago, unfortunately.

My case

In my particular case, I am creating a Wiki-style plugin that manages information of a custom post type. Besides the basic fields of a custom post type ( title, author, content, featured image), I have a few other fields that I would like to keep track of versions.

My attempt

As I already mentioned about, I have found an article by John Blackbourn (and thanks John!) from back in 2012 that pointed me in the right direction. But yet, I can't get it to work. I might be missing something, maybe I have a misconception of how WordPress revisions work, or maybe I just need to sleep on it and it will come to me in the morning. Who knows, but I truly need your help. Here is what I got so far:

To save a metadata revision of a single field, straight from the article mentioned above:

function my_plugin_save_post( $post_id, $post ) {

    if ( $parent_id = wp_is_post_revision( $post_id ) ) {

        $parent  = get_post( $parent_id );
        $my_meta = get_post_meta( $parent->ID, 'my_meta', true );

        if ( false !== $my_meta )
              add_metadata( 'post', $post_id, 'my_meta', $my_meta );
    }

} add_action( 'save_post', 'my_plugin_save_post' );

It looks really straight forward, right? But guess what, it fails at the if ( $parent_id) {...} condition. Because $post_id isn't a revision. How is this suppose to work if it is never a revision? I don't get it. I thought the hook 'save_post' sends the current $post_id and not a child-revision. What am I doing wrong?

Caio Mar
  • 2,344
  • 5
  • 31
  • 37

1 Answers1

1

The save_post hook is fired when you save a post, but it gets triggered not only for the actual post but also for the revision that gets inserted at the same time.

So wp_is_post_revision( $post_id ) will return false when WordPress saves the actual post to the database, and it'll return true when it inserts the revision. This is when the code in the conditional statement will fire.

John Blackbourn
  • 791
  • 1
  • 8
  • 14