This WooCommerce snippet checks the cart for two specific products. If both are present, it applies a discount to one of them based on its price and quantity. The discount is added as a negative fee during cart calculation. The code avoids running in the admin area unless it’s an AJAX request, and can be customised by replacing the product IDs and discount rate.

  • Replace 1234 with the ID of the product that must be in the cart to trigger the discount (referred to as Product A).
  • Replace 5678 with the ID of the product that will receive the discount (referred to as Product B).
  • Change the discount rate by editing the 0.4 value. For example, use 0.2 for a 20% discount or 0.5 for 50%.
  • Change the label shown at checkout by editing ‘Special Discount’.

You can find product IDs by going to the Products section in your WordPress dashboard and hovering over the product name — the ID will appear in the URL at the bottom of your browser window.

function bb_discount_for_specific_product($cart) {
    if (is_admin() && !defined('DOING_AJAX')) {
        return;
    }

    // Set your product IDs here
    $trigger_product_id = 1234; // Product A - must be in cart to activate discount
    $discounted_product_id = 5678; // Product B - receives the discount

    // Set your discount rate here
    $discount_rate = 0.4;

    $discount = 0;
    $trigger_in_cart = false;
    $discounted_qty = 0;
    $discounted_price = 0;

    foreach ($cart->get_cart() as $cart_item) {
        $product_id = $cart_item['product_id'];

        if ($product_id == $trigger_product_id) {
            $trigger_in_cart = true;
        }

        if ($product_id == $discounted_product_id) {
            $discounted_qty = $cart_item['quantity'];
            $discounted_price = $cart_item['data']->get_price();
        }
    }

    if ($trigger_in_cart && $discounted_qty > 0) {
        $discount = ($discounted_price * $discounted_qty) * $discount_rate;
        $cart->add_fee('Special Discount', -$discount);
    }
}

add_action('woocommerce_cart_calculate_fees', 'bb_discount_for_specific_product', 20, 1);

Add the PHP to your child theme’s functions.php file, or a code snippets plugin.

Code snippets are offered ‘as is’ and no support is provided. If you have customisation requirements, feel free to contact me for a quote.

Pro Pass Membership

Want access to all current and future child themes, kits, and our B&B Blocks library for Kadence for one low annual price?

Brand & Build Pro Pass

Latest

In the shop

  • Kadence
    Lane Wordpress Theme for KadenceLane Wordpress Theme for Kadence

    for content creators

    £175.00

    View Details 🡢

  • Kadence
    Liora Child Theme for KadenceLiora Child Theme for Kadence

    for bloggers

    £175.00

    View Details 🡢