So combined with that code for setting the value before it's inserted in the db, you also need to add this code to add the post ID to an array stored in the user's meta (after it has been updated):
add_action( 'wp_insert_post', 'smyles_update_user_products', 10, 3 );
function smyles_update_user_products( $post_ID, $post, $update ) {
if ( $post->post_type !== 'product' ) {
return;
}
$user_id = get_current_user_id();
if ( ! empty( $user_id ) ) {
$user_products = get_user_meta( $user_id, 'user_products', true );
if ( is_array( $user_products ) && ! in_array( $post_ID, $user_products ) ) {
$user_products[] = $post_ID;
} else {
$user_products = array( $post_ID );
}
update_user_meta( $user_id, 'user_products', $user_products );
}
}
Then add a hook when the user's meta is updated, to then trigger the update on all of those associated posts:
add_action( 'updated_user_meta', 'smyles_update_post_on_user_desc_update', 10, 4 );
function smyles_update_post_on_user_desc_update( $meta_id, $user_id, $meta_key, $_meta_value ){
if( $meta_key !== 'some_meta_key' ){
return;
}
// Probably not necessary, but just in case
if( ! empty( $user_id ) ){
$user_products = get_user_meta( $user_id, 'user_products', true );
if( ! empty( $user_products ) && is_array( $user_products ) ){
// Remove our action to prevent loop
remove_action( 'wp_insert_post_data', 'smyles_insert_user_product_data', 10 );
foreach( (array) $user_products as $product_id ){
$my_post = array(
'ID' => $product_id,
'post_content' => $_meta_value,
);
wp_update_post( $my_post );
}
// Add it back after were done
add_action( 'wp_insert_post_data', 'smyles_insert_user_product_data', 10, 2 );
}
}
}
You may be able to just remove setting the actual post_content
value and just call wp_update_post
(and remove the remove_action
and add_action
calls), allowing that action to still handle this (but i haven not tested the code so i'm not sure if WordPress will still do an update if all you pass is just the ID
)