WP SITES

3085 Coded Tutorials & 288 Plugins

Offer discounted product if order quantity below x number in woocommerce cart

This code displays a message on the cart page to entice customers to buy more products if their cart quantity is below a set threshold. You can tweak the code to work with any product category, price and discount percentage.

How It Works

  • The code loops through cart items looking for products assigned the t-shirt category
  • It counts the number of products in the cart
  • If there’s less than the threshold ( in this case 5 t shirts ) it calculates the price of adding more with discounts
  • It displays a message before the checkout with the discounted price of the product

Cart Messages

Messages are displayed based on quantity already in cart.

  • If the customer has a total quantity of 2, it displays a message “Add another for a discounted price of $18”.
  • If the customer has a total quantity of 3, it displays a message “Add another for a discounted price of 1$7”.
  • If the customer has a total quantity of 4, it displays a message “Add another for a discounted price of $16”.

Code

Here’s the code you can add to your child themes functions file or custom code snippets plugin.

add_action('woocommerce_before_cart', 'offer_discounted_tee_message');
function offer_discounted_tee_message() {

    if ( ! WC()->cart) return;

    $cart = WC()->cart->get_cart();
    $tshirt_category = 't-shirts'; // Update this to match your actual category slug
    $tshirt_price = 20; // Set your base T-shirt price
    $tshirt_count = 0;

    // Loop through cart items and count T-shirts
    foreach ($cart as $cart_item) {
        $product = wc_get_product($cart_item['product_id']);
        if ($product && has_term($tshirt_category, 'product_cat', $product->get_id())) {
            $tshirt_count += $cart_item['quantity'];
        }
    }

    if ($tshirt_count > 0 && $tshirt_count < 5) {
        // Discount structure
        $discounts = [
            2 => 0.05,
            3 => 0.10,
            4 => 0.15,
            5 => 0.20
        ];

        // Determine the discount for the next quantity
        $next_quantity = $tshirt_count + 1;
        $next_discount = isset($discounts[$next_quantity]) ? $discounts[$next_quantity] : 0.20;

        // Calculate the discounted price for adding one more
        $next_price = $tshirt_price * (1 - $next_discount);

        // Display the message on the cart page
        wc_print_notice("You can add another T-shirt for just <strong>£" . number_format($next_price, 2) . "</strong>!", 'notice');
    }
}

Related

Leave a Reply

New Plugins