The code snippet helps to implement the scenario where customers can purchase items from Category X and receive a discount on items from Category Y. The discount is applied to Category Y items only when Category X items contribute to the cart subtotal of the items in the customer’s cart. The discount gets applied when the subtotal of line items of category X exceeds the minimum subtotal threshold i.e. defined in the code.
add_action('template_redirect', 'ts_buy_x_get_y_discount'); function ts_buy_x_get_y_discount() { if (!is_admin()) { global $woocommerce; $category_x_id = 60; // Category ID for Category X $category_y_id = 16; // Category ID for Category Y $min_subtotal = 200; // Minimum subtotal for the discount // Flag to check if the discount has been applied $discount_applied = false; // Calculate cart subtotal $cart_subtotal = WC()->cart->subtotal; // Loop through cart items and apply the discount to Category Y foreach (WC()->cart->get_cart() as $inner_cart_item_key => $inner_cart_item) { // Check if the product is in Category Y $product_cats_id_incart_y = wc_get_product_term_ids($inner_cart_item['data']->get_id(), 'product_cat'); if (!is_admin() && in_array($category_y_id, $product_cats_id_incart_y)) { // Apply a discount for each item in Category Y if cart subtotal exceeds $200 if ($cart_subtotal > $min_subtotal) { $discount_percentage = 10; // You can set the desired discount percentage $original_price = floatval($inner_cart_item['data']->get_price()); $discount_amount = $original_price * $discount_percentage / 100; $new_price = $original_price - $discount_amount; // Set the new discounted price $inner_cart_item['data']->set_price($new_price); // Set the flag to indicate that the discount has been applied $discount_applied = true; } } } // If the discount is applied, you may need to update the cart totals if ($discount_applied) { WC()->cart->calculate_totals(); } } }
Output
When the customer adds multiple products to the cart, the discount will only be applied to products in Category Y if there are products from Category X present in the cart and when their subtotal exceeds the specified minimum of $200 as specified in the code.
On another scenario where the products of category X don’t meet the specified minimum threshold amount then the discount is not applied to the line items of category Y present in the cart.
Alternatively, you can also automatically add and apply discount on product B based on cart subtotal in WooCommerce.