php - 保存帖子并添加帖子元执行两次

标签 php wordpress function hook

我正在尝试在保存帖子时添加或更新两个帖子元。如果是新帖子则添加,如果存在则更新,但此函数在数据库中创建四个而不是两个元。

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/

相关文章:

php - MATCH AGAINST SQL 注入(inject)预防和 wpdb->prepare

javascript - 如果 php 抛出警告,如何将数据从 php 发送到 jquery ajax 成功处理程序?

css - 当我点击一个链接时,如何使这个菜单在 Wordpress 上消失?

MYSQL 查询连接表

jsp - 在 JSP 中声明函数?

php - 在 utf8 类中设置 ascii 常量

javascript - 如何限制每页 php 中显示的文章数量(从 RSS 检索)? (例如每页 10 篇文章)

php - WordPress 自定义 SQL 案例排序优先级

arrays - 如何创建一个函数来将字符串与字典中的字符串数组进行比较并根据键分配点?

c++ - 实现递归函数以查找路径的问题