Woocommerce 常规价格未更新

Woocommerce regular price not getting updated

我在我的 woocommerce 产品中添加了一个名为 'Discount_Percentage' 的 ACF 字段。我想在将正常价格留空时根据折扣百分比计算正常价格,或者在折扣百分比字段为空时计算折扣百分比。 以下是我的代码片段:

function wc_update_discount_and_sale_price($post_id) {
 $selling_price = get_field('_price');
 $mrp = get_field('_regular_price');
 $discount_percentage = get_field('discount_percentage');

 if(empty($selling_price) && empty($discount_percentage)){
 return;
 }

 if(!empty($selling_price) && empty($discount_percentage)){
  $discount_value = (($mrp - $selling_price)*100)/($mrp);
   update_field("discount_percentage",$discount_value,$post_id);
   return;
 }

 if(empty($selling_price) && !empty($discount_percentage)){   //not working
 $selling_price = $mrp*(100 - $discount_percentage)/100;
 update_post_meta($post_id,'_price', $selling_price);
 }
}
 add_action('save_post','wc_update_discount_and_sale_price');

前两个 if 语句运行良好。在第三个 if 语句中,没有填充正常价格。

更新:_price 更改为 _sale_price 有效。

您应该在您的第三个条件中删除此 empty($selling_price) &&,因为根据您的第二个条件,$selling_price 不是空的,正如您所说,您的第一个和第二个条件工作正常。所以在这种情况下,除非 $selling_price 为空,否则您的第三个条件将不成立。试试下面的代码。

if( !empty( $discount_percentage ) ){   //not working
    $selling_price = $mrp * ( 100 - $discount_percentage ) / 100;
    update_post_meta( $post_id, '_price', $selling_price );
}