因此,结合用于在插入db之前设置值的代码,您还需要添加此代码以将post ID添加到存储在用户元中的数组中(更新后):
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 );
}
}
然后在更新用户的meta时添加一个钩子,以触发所有相关帖子的更新:
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 );
}
}
}
你
may 只需删除实际设置
post_content
价值观和通话
wp_update_post
(并拆下
remove_action
和
add_action
调用),允许该操作仍能处理此问题(但我尚未测试代码,因此我不确定WordPress是否仍会进行更新,如果您只通过
ID
)