:::: MENU ::::

WooCommerce apply discount programmatically

WooCommerce apply discount programmatically

Today we talk about how WooCommerce apply discount programmatically. Sometimes you need to add the discount bases on some condition. Follow is the snippets how can you achieve the functionality.

Simple Product

To apply the discount on simple products use the following code.

add_filter( 'woocommerce_product_get_price' , 'products_custom_price' , 5, 2 );
function products_custom_price( $price, $product ){
      $discount = 10;
      $product_id = $product->get_id();
      if( $product_id == '20' ){
          return $price - $discount;
      }
}

Variable Product

To apply the discount on variable products use the following code.

add_filter( 'woocommerce_product_variation_get_price' , 'variation_custom_price' , 99, 2 );
function variation_custom_price( $price, $variation ){
        //Apply Discount by matching the parent Product
       $product = wc_get_product($variation->get_parent_id());
       if( '20' == $product->get_id() ){
             return $price - $discount;
       }
       //Apply Discount by matching the Product Variation
       if( '20' == $variation->get_id() ){
             return $price - $discount;
       }
}
Author: Qaisar Satti
Category: WooCommerce
Last Modified: September 29, 2020


So, what do you think ?