The goal here is to create an automatic percentage (or amount see further below) discount when 2 specific products are added to the cart.
Essentially creating a bundle discount, without the need for a plugin!
First thing we need to find out is the ID numbers of the 2 products you are wanting to bundle for the discount.
You can do this by going to Products -> All Products, click on one of the products and in the url field of your browser look for this number:
So the ID number for this product would be 1188, do this same action for the 2nd product.
Now that we have both ID numbers, we can get to the function.
In the functions.php add the below:
function discount_on_cart_add($cart){ //Update the below variables to suit your needs: $product_id = 1019; //Product ID One $product_idt = 1018; //Product ID Two $percentage = 10; //The percentage discount to apply //end settings if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; //Check if both product ID's have been added to the cart if( WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product_id ) ) && WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product_idt ) ) ) { $subtotal = $cart->subtotal; //Get the subtotal $discount = ( $subtotal / 100 ) * $percentage; //Calculate our discount //Give % discount on the subtotal and add a notice $cart->add_fee('Discount '.$percentage.'%', -$discount ); if( isset($discount) ){ wc_add_notice( __( 'Bundle Discount Applied', 'theme_slug' ), 'success' ); } } } add_action( 'woocommerce_cart_calculate_fees', 'discount_on_cart_add', 10,1 );
Modify the above variables to include your product numbers and your discount percentage.
Update the functions.php and now check it out on your front end!
Want to offer a dollar amount instead? We can adjust the function to subtract an amount instead like so:
function discount_on_cart_add_amount($cart){ //Update the below variables to suit your needs: $product_id = 1136; //Product ID One $product_idt = 1137; //Product ID Two $amount = 10; //The amount discount to apply //end settings if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; //Check if both product ID's have been added to the cart if( WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product_id ) ) && WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product_idt ) ) ) { // Give amount discount on the subtotal and add a notice $cart->add_fee( sprintf( __( 'Discount', 'woocommerce')), -$amount); } } add_action( 'woocommerce_cart_calculate_fees', 'discount_on_cart_add_amount', 10,1 );
*Note the codes above will only work on Simple products (not products with variations)