Adding existing user custom field value to a woocommerce product [closed]

You can do this with an action when a new product is inserted (and not when updated). As you did not specify the meta key this field is stored under the user as, OR the meta key of where you want it stored on the product:

add_action( 'wp_insert_post', 'smyles_insert_user_product_data', 10, 3 );

function smyles_insert_user_product_data( $post_ID, $post, $update ){

    if( $update || $post->post_type !== 'product' ){
        return;
    }

    $user_id = get_current_user_id();

    if( $user_id ){
        $short_bio = get_user_meta( $user_id, 'some_meta_key', true );
        if( ! empty( $short_bio ) ){
            update_post_meta( $post_ID, 'product_meta_key', $short_bio );
        }
    }
}

This assumes that the “short bio” is stored in the user’s meta, so you need to figure out that meta key and replace some_meta_key in the code above with correct one for the user.

You then also need to define what meta key you want to use to set that value in the product with, and replace product_meta_key above.

To find the user meta key used, you can use my User Meta Display plugin: https://wordpress.org/plugins/user-meta-display/ (it’s a bit out-dated but still works)

UPDATE:

To update the description (post_content) before data in inserted into the database use this instead:

add_action( 'wp_insert_post_data', 'smyles_insert_user_product_data', 10, 2 );

function smyles_insert_user_product_data( $data, $postarr ){

    // Non-empty ID means it's an update (don't want to modify on update)
    if( ! empty( $postarr['ID'] ) || ! array_key_exists( 'post_type', $postarr ) || $postarr['post_type'] !== 'product' ){
        return $data;
    }

    $user_id = get_current_user_id();

    if( $user_id ){
        $short_bio = get_user_meta( $user_id, 'some_meta_key', true );
        if( ! empty( $short_bio ) ){
            $short_bio = wp_kses( $short_bio, true );
            $data['post_content'] = wp_slash( $short_bio );
        }
    }

    return $data;
}

Leave a Comment