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;
       }
}

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply