Support

Account

Home Forums General Issues How to update Woocommerce product meta using code snippet

Solved

How to update Woocommerce product meta using code snippet

  • 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)){
     $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.
    Thank you so much!

  • Update:
    Replaced _price with _sale_price made the job done.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.