The purpose of the code is to automatically add a free product (Product B) to the cart when the total value of items in the cart exceeds $100. Additionally, if the free product is already in the cart, a 20% discount is applied to that product.
function ts_aapc_add_product_to_cart() { $cart_total = 500; // Replace 500 with the desired amount for which the free product should be added to the cart. $discount_percentage = 50; $free_product_id = 470; // Product Id of the free product which will get added to the cart // Check if the cart total meets the condition if ( WC()->cart->get_cart_contents_total() >= $cart_total ) { $found = false; // Check if the free product is already in the cart foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $_product = $cart_item['data']; if ( $_product->get_id() == $free_product_id ) { $found = true; // Apply a 50% discount on the added free product $discount_amount = $_product->get_price() * $discount_percentage / 100; $_product->set_price( $_product->get_price() - $discount_amount ); // Break the loop once the free product is found break; } } // If the free product is not found, add it if ( ! $found ) { $free_product = wc_get_product( $free_product_id ); WC()->cart->add_to_cart( $free_product_id ); } } } add_action( 'template_redirect', 'ts_aapc_add_product_to_cart', 20 ); // Priority set to 20 to ensure it runs after WooCommerce calculates totals
Output
Let’s look into the actual product price of product B which is applied with the discount price.
When the customer adds the items with values that exceed the defined cart subtotal amount(in this case, $100), then product B is automatically added to the cart with the discount of 20% being applied to it.
Similarly, you can also implement buy 1 get 2 free action in WooCommerce based on different scenarios such as cart total, based on categories, and on website visit, etc.