1

I wanted to save custom field values to the revision history. The following URL had code that helped me achieve that (http://carolandrews.co.uk/saving-revisions-for-custom-post-type-meta-data/).

The problem is that I have to click the "Update" button twice in order for it to show up on the revisions history. Clicking "Update" once does update values correctly, it just does not show in revision history unless I click it twice.

Here is the code:

function ca_members_fields(){  global $CustomPress_Core;   $member_fields=$CustomPress_Core->get_custom_fields_set('book');   return $member_fields; }

add_filter( '_wp_post_revision_fields','ca_member_fields', 10, 1 );

function ca_member_fields( $fields ) {
  $members_fields=ca_members_fields();
   foreach($members_fields as $fieldname=>$members_field){ 
     $fields['ct_'.$fieldname] = $members_field['field_title']; 
   }
 return $fields;
}

function ca_field( $value, $field_name,$post ) { 
  $members_fields=ca_members_fields(); 
   foreach($members_fields as $fieldname=>$members_field){ 
    if($field_name==$fieldname){ 
     $value= get_metadata( 'post',$post->ID, 'ct_'.$fieldname , true ); 
    } 
   } 
  return $value; 
}

function ca_custom_admin_head() {
 $members_fields=ca_members_fields();
  foreach($members_fields as $fieldname=>$members_field){
   add_filter( '_wp_post_revision_field_'.'ct_'.$fieldname, 'ca_field', 10, 4 );
 }
}
add_action( 'admin_head', 'ca_custom_admin_head' );

add_action( 'save_post','ca_save_member_revision', 10, 2 );
function ca_save_member_revision( $post_id, $post ) {
   if ( $parent_id = wp_is_post_revision( $post_id ) ) {
    $parent = get_post( $parent_id );
         if($parent->post_type='book'){
                $members_fields=ca_members_fields();
                foreach($members_fields as $fieldname=>$members_field){
                    $meta = get_post_meta( $parent->ID, 'ct_'.$fieldname, true );
                    if ( false !== $meta ){
                         add_metadata( 'post', $post_id, 'ct_'.$fieldname, $meta );
                    }
               }
           }     
      }
}

add_action( 'wp_restore_post_revision',    'ca_restore_revision', 10, 2 );
function ca_restore_revision( $post_id, $revision_id ) {
    $post     = get_post( $post_id );
    $revision = get_post( $revision_id );
    if($post->post_type='book'){
        $members_fields=ca_members_fields();
        foreach($members_fields as $fieldname=>$members_field){     
           $meta = get_metadata( 'post', $revision->ID, 'ct_'.$fieldname, true );
           if ( false !== $meta ){
            update_post_meta( $post_id, 'ct_'.$fieldname, $meta );
           }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.