WordPress 4.4+ : How to revision CPT + metadata

I’m not one-hundred percent sure, what is failing for you, but I can tell you, generally it should work. The proof is following under thirdly. Before I have some remarks for you:

Firstly, my guess would be, that it indeed isn’t failing silently, but while doing an AJAX process. So make use of a tool like FireBug to take a closer look at that.

Secondly, I’m pretty sure get_the_ID() – as used in your code – will get you the parent posts ID, which certainly isn’t what you want. If I’m seeing it correctly, then you can replace all occurrences with $post->ID – so that is easy enough for a change.

Thirdly, as you are more or less following the »John Blackbourn«-approach, I took his example code as plugin to take a closer look myself. Less cleanup work to do, in comparison to working with your code. But anyway, below you see the code with the small necessary changes, see comments for details, to make it work.

/*
Plugin Name: Post Meta Revisions
Description: Revisions for the 'foo' post meta field
Version:     http://wordpress.stackexchange.com/questions/221946
Author:      John Blackbourn
Plugin URI:  http://lud.icro.us/post-meta-revisions-wordpress
*/

function pmr_fields( $fields ) {
    $fields['foo'] = 'Foo';
    return $fields;
}

// global $revision doesn't work, using third parameter $post instead
function pmr_field( $value, $field, $post ) {
    return get_metadata( 'post', $post->ID, $field, true );
}

function pmr_restore_revision( $post_id, $revision_id ) {
    $post     = get_post( $post_id );
    $revision = get_post( $revision_id );
    $meta     = get_metadata( 'post', $revision->ID, 'foo', true );

    if ( false === $meta )
        delete_post_meta( $post_id, 'foo' );
    else
        update_post_meta( $post_id, 'foo', $meta );
}

function pmr_save_post( $post_id, $post ) {
    if ( $parent_id = wp_is_post_revision( $post_id ) ) {
        $parent = get_post( $parent_id );
        $meta = get_post_meta( $parent->ID, 'foo', true );

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

// we are using three parameters
add_filter( '_wp_post_revision_field_foo', 'pmr_field', 10, 3 );
add_action( 'save_post',                   'pmr_save_post', 10, 2 );
add_action( 'wp_restore_post_revision',    'pmr_restore_revision', 10, 2 );
add_filter( '_wp_post_revision_fields',    'pmr_fields' );

After giving it a quick test, it seems to work quite well.

Leave a Comment