0

Each author has a single post in a CPT. In their CPT post they have a custom field.

Each author can also post to a normal post type as much as they like.

How can I copy the custom field of the user's CPT post copied to all their normal post type posts they subsequently post.

Any help greatly appreciated.

1

You can use the wp_insert_post action for when a user creates/saves a "normal" post, then find their custom post and copy over any fields you need:

function wpse_203349_copy_post_meta( $post_ID, $post, $update ) {
    if ( $post->post_type !== 'post' )
        return;

    $users_custom_posts = get_posts(
        array(
            'posts_per_page' => 1,
            'post_author' => $post->post_author,
            'post_type' => 'custom_post_type',
        )
    );

    if ( ! $users_custom_posts )
        return; // This author doesn't currently have any custom posts

    $fields = get_post_custom( $users_custom_posts[0]->ID );

    foreach ( $fields as $field => $value ) {
        if ( $field[0] !== '_' && ( empty( $value[0] ) || ! is_array( $value[0] ) ) ) // Ignore "private" fields (prefixed with an underscore or serialized data)
            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()
    }
}

add_action( 'wp_insert_post', 'wpse_203349_copy_post_meta', 10, 3 );
  • Thanks very much, it's copying the custom field, but not the value of the field. – Pete Sep 22 '15 at 13:05
  • See revised answer. – TheDeadMedic Sep 22 '15 at 13:10
  • Still no values, oh and it triplicates every custom field of the new post when I publish it. Hot Diggity! – Pete Sep 22 '15 at 13:19
  • [line 2] if ( $post->post_type !== 'post' ) ... this doesn't change right? I've only edited the CPT name in line 9 – Pete Sep 22 '15 at 13:21
  • Each time the post is updated it adds more copies of the post's custom fields. – Pete Sep 22 '15 at 13:29

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.