Search code examples
wordpressadvanced-custom-fieldshook-woocommercecode-snippets

Woocommerce regular price not getting updated


I have added an ACF field named 'Discount_Percentage' to my woocommerce product. I want to calculate the regular price based on the discount percentage when I leave the regular price empty OR calculate the discount percentage when the discount percentage field is empty. Following is my code snippet:

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');

The first two if statements are working fine. In the third if statement the regular price doesn't get populated.

UPDATE: Changed _price to _sale_price worked.


Solution

  • You should remove this empty($selling_price) &&in your 3rd condition because $selling_price is not empty as per your 2nd condition and as you said your 1st and 2nd condition working fine. so in this case your 3rd condition will not true unless $selling_price is empty. try the below code.

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