Advertisement
pjeaje

Copy an author's cpt custom field/s to the author's normal p

Sep 23rd, 2015
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.01 KB | None | 0 0
  1. function wpse_203349_copy_post_meta( $post_ID, $post, $update ) {
  2.  
  3.     if ( $post->post_type !== 'post' )
  4.  
  5.         return;
  6.  
  7.  
  8.  
  9.     $users_custom_posts = get_posts(
  10.  
  11.         array(
  12.  
  13.             'posts_per_page' => 1,
  14.  
  15.             'post_author' => $post->post_author,
  16.  
  17.             'post_type' => 'custom_post_type',
  18.  
  19.         )
  20.  
  21.     );
  22.  
  23.  
  24.  
  25.     if ( ! $users_custom_posts )
  26.  
  27.         return; // This author doesn't currently have any custom posts
  28.  
  29.  
  30.  
  31.     $fields = get_post_custom( $users_custom_posts[0]->ID );
  32.  
  33.  
  34.  
  35.     foreach ( $fields as $field => $value ) {
  36.  
  37.         if ( $field[0] !== '_' && ( empty( $value[0] ) || ! is_array( $value[0] ) ) ) // Ignore "private" fields (prefixed with an underscore or serialized data)
  38.  
  39.             add_post_meta( $post_ID, $field, empty( $value[0] ) ? '' : $value[0], true /* Unique */ ); // If the field already exists, it won't be overwritten, unlike update_post_meta()
  40.  
  41.     }
  42.  
  43. }
  44.  
  45.  
  46.  
  47. add_action( 'wp_insert_post', 'wpse_203349_copy_post_meta', 10, 3 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement