我正在尝试在保存帖子时添加或更新两个帖子元。如果是新帖子则添加,如果存在则更新,但此函数在数据库中创建四个而不是两个元。
add_action( 'save_post', 'add_rewards');
global $WCFM, $WCFMmp;
function add_rewards ($product_id){
if($product_id){
$post_type = get_post_type($product_id);
if($post_type == 'product'){
$product = wc_get_product( $product_id );
$reg_price = $product->get_regular_price();
$sal_price = $product->get_sale_price();
$pric = $product->get_price();
add_post_meta($product_id,'main_reward', $reg_price);
add_post_meta($product_id,'sub_reward', $sal_price);
}
}
}
最佳答案
正如 save_post
手册中所述,您应该使用 save_post_{$post->post_type}
来最大限度地减少对其他帖子类型的 save_post 调用。检查自动保存也是一个好主意。
此外,如果您使用 update_post_meta
而不是 add_post_meta
,您最终将只得到每个实例的一个实例。正如该功能的手册中所解释的那样:
If the meta field for the post does not exist, it will be added and its ID returned. Can be used in place of add_post_meta().
add_action( 'save_post_product', 'so71077799_add_rewards', 99, 1 );
function so71077799_add_rewards( $product_id ) {
// Check to see if we are autosaving, if so, exit.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( isset( $_POST['_regular_price'] ) ) {
update_post_meta( $product_id, 'main_reward', number_format( floatval( $_POST['_regular_price'] ), '2' ) );
}
if ( isset( $_POST['_sale_price'] ) ) {
update_post_meta( $product_id, 'sub_reward', number_format( floatval( $_POST['_sale_price'] ), '2' ) );
}
}
关于php - 保存帖子并添加帖子元执行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71077799/