Home / Admin / Woocommerce: How to add minimum amount for different categories with different amount per category with different notice.
Duplicate Snippet

Embed Snippet on Your Site

Woocommerce: How to add minimum amount for different categories with different amount per category with different notice.

WooCommerce: Display Minimum Order Amount Notices by Category
This code snippet adds functionality to your WooCommerce store to enforce minimum order amounts for specific product categories. It displays informative notices to guide users towards meeting the minimum requirements.

Here’s a breakdown of the code and its functionalities:

1. Displaying Category Notices on Single Product Pages:

The display_category_notice function checks if the current product belongs to a category with a minimum order amount.
It retrieves category information and calculates the total amount of products from that category in the user’s cart.
If the minimum amount isn’t met, a notice displays the category name, current total for the category, remaining amount to reach the minimum, and a list of category products in the cart.
For categories where the minimum amount is already met, a congratulatory message is displayed.
2. Checking Minimum Amounts in the Cart:

The check_cart_outlet_items function iterates through defined categories with minimum amounts.
It checks if there are products from each category in the cart and calculates the total amount spent on those products.
If the minimum amount for a category isn’t met, a notice is displayed with details like the category name, minimum amount needed, and a list of category products in the cart.
This function also removes the “Proceed to Checkout” button from the cart page and the “Place Order” button from the checkout page if the minimum requirements aren’t met.
3. Customizing Error Notice Styles (Optional):

The custom_error_notice_styles function adds custom CSS styles to the error notices displayed for unmet minimum amounts. You can modify the colors used for category links, product names, and amounts.
4. Enforcing Minimum Amounts at Checkout:

The limit_checkout_until_thresholds_met function verifies if all minimum thresholds for defined categories are met in the cart.
It checks each category’s total and compares it to the minimum amount.
If any category falls short, an error message is displayed, and the “Place Order” button is removed from the checkout page.
5. Displaying Checkout Notice (Optional):

The display_checkout_notice_if_thresholds_not_met function (similar to check_cart_outlet_items) checks for unmet minimum amounts at the checkout page and displays informative notices if necessary.
Overall, this code snippet enhances the user experience by:

Informing users about minimum order requirements per category.
Guiding users towards adding more products to meet the minimums.
Preventing users from proceeding to checkout until all minimum thresholds are satisfied.

Code Preview
php
<?php
// Display notice on single product page for specific category
add_action('woocommerce_before_single_product_summary', 'display_category_notice');
function display_category_notice() {
    global $product;
    if (!$product) {
        return; // Exit if $product is not defined
    }
    $categories = get_categories_with_minimum_amount();
    $cart_items = WC()->cart->get_cart();
    $notices = array();
    foreach ($categories as $category_name => $minimum_amount) {
        if (has_term($category_name, 'product_cat', $product->get_id())) {
            $category_total = 0;
            foreach ($cart_items as $cart_item) {
                if (has_term($category_name, 'product_cat', $cart_item['product_id'])) {
                    $category_total += $cart_item['line_total'];
                }
            }
            $category_balance = $minimum_amount - $category_total;
            if ($category_balance <= 0) {
                $notices[] = sprintf(__('Congratulations! You have met the minimum order amount for the category "%s".', 'your-text-domain'), $category_name);
                continue; // Skip category if the minimum amount is already met
            }
            $product_names = getProductNamesByCategory($category_name);
            $category_link = get_term_link($category_name, 'product_cat');
            if (!is_wp_error($category_link)) {
                $notice = sprintf(
                    __('This product belongs to the category "<a href="%s" class="category-product">%s</a>". Current Total cart amount of products from this category: <span class="amount">%s</span>.<br> Amount needed to meet the minimum: <span class="amount">%s</span>. Category products in the Cart: <span class="category-products">%s</span>', 'your-text-domain'),
                    esc_url($category_link), esc_html($category_name), wc_price($category_total), wc_price($category_balance), $product_names
                );
                echo '<div class="woocommerce-info">' . $notice . '</div>';
            }
        }
    }
    if (!empty($notices)) {
        wc_add_notice(implode('<br>', $notices), 'success');
    }
}
// Get product names by category
function getProductNamesByCategory($category_name) {
    $product_names = array();
    foreach (WC()->cart->get_cart() as $cart_item) {
        if (has_term($category_name, 'product_cat', $cart_item['product_id'])) {
            $product = wc_get_product($cart_item['product_id']);
            $product_names[] = sprintf('<a href="%s" class="product-name">%s</a>', esc_url($product->get_permalink()), esc_html($product->get_name()));
        }
    }
    return implode(', ', $product_names);
}
// Check cart items for category minimum amount
add_action('woocommerce_check_cart_items', 'check_cart_outlet_items');
function check_cart_outlet_items() {
    $categories = get_categories_with_minimum_amount();
    $cart = WC()->cart;
    $cart_items = $cart->get_cart();
    $notices = array();
    foreach ($categories as $category_name => $minimum_amount) {
        $found = false;
        $category_total = 0;
        $product_names = array();
        foreach ($cart_items as $cart_item) {
            if (has_term($category_name, 'product_cat', $cart_item['product_id'])) {
                $found = true; // A product in the category is found
                $category_total += $cart_item['line_total'];
                $product = wc_get_product($cart_item['product_id']);
                $product_names[] = sprintf('<a href="%s" class="product-name">%s</a>', esc_url($product->get_permalink()), esc_html($product->get_name()));
            }
        }
        if ($found && $category_total < $minimum_amount) {
            $category_link = get_term_link($category_name, 'product_cat');
            if (!is_wp_error($category_link)) {
                $notices[] = sprintf(
                    __('Minimum order amount for category <a href="%s" class="category-link">%s</a> is %s. Add <span class="amount">%s</span> to meet the minimum. Total amount of products in this category already in the cart: <span class="amount">%s</span>. Category products: <span class="category-products">%s</span>', 'your-text-domain'),
                    esc_url($category_link), esc_html($category_name), wc_price($minimum_amount), wc_price($minimum_amount - $category_total), wc_price($category_total), implode(', ', $product_names)
                );
            }
        }
    }
    if (!empty($notices)) {
        wc_add_notice(implode('<br>', $notices), 'error');
        restrict_checkout_buttons();
    }
}
function restrict_checkout_buttons() {
    if (WC()->cart->total < array_sum(get_categories_with_minimum_amount())) {
        remove_action('woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20);
        if (is_checkout()) {
            remove_action('woocommerce_checkout_order_review', 'woocommerce_checkout_payment', 20);
        }
    }
}
// Function to get the categories with minimum amount
function get_categories_with_minimum_amount() {
    return array(
        'Cleanser' => 1000,
        'Moisturizer' => 250,
        'Cat 3' => 500,
        'Cat 4' => 500,
    );
}
// Custom error notice styles
add_action('wp_head', 'custom_error_notice_styles');
function custom_error_notice_styles() {
    echo '
    <style>
		.woocommerce-error {
			background-color: #000000;
			border: 1px solid #ff3333;
			color: #ffffff;
			padding: 10px;
			margin-bottom: 20px;
			text-align: center;
		}
		.woocommerce-error strong {
			font-weight: bold;
		}
		.woocommerce-error ul {
			margin: 0;
			padding-left: 20px;
		}
		.woocommerce-error li {
			list-style-type: disc;
		}
		.woocommerce-error .amount {
			color: #ff3333;
			font-weight: bold;
			border-radius: 20px;
			padding: 5px 10px;
		}
		.woocommerce-error .category-link {
			color: #8AFF33;
			text-decoration: none;
		}
		.woocommerce-error .category-link:hover {
			text-decoration: underline;
		}
		.woocommerce-error .category-product {
			color: #00ff00;
			cursor: pointer;
		}
		.woocommerce-error .product-name {
			color: #3366cc;
			cursor: pointer;
			text-decoration: underline;
		}
		.woocommerce-info {
			background-color: #000000;
			border: 1px solid #ffffff;
			color: #ffffff;
			padding: 10px;
			margin-bottom: 20px;
			text-align: center;
		}
		.woocommerce-info .amount {
			color: #ff3333;
			font-weight: bold;
			border: 1px solid #ff3333;
			border-radius: 20px;
			padding: 5px 10px;
		}
		.woocommerce-info .category-product {
			color: #00ff00;
			cursor: pointer;
		}
		.woocommerce-info .product-name {
			color: #3366cc;
			cursor: pointer;
			text-decoration: underline;
		}
 	</style>
    ';
}
// Limit checkout until all thresholds for set categories are met
add_action('woocommerce_checkout_process', 'limit_checkout_until_thresholds_met');
function limit_checkout_until_thresholds_met() {
    $categories = get_categories_with_minimum_amount();
    $cart = WC()->cart;
    $cart_items = $cart->get_cart();
    $all_thresholds_met = true;
    foreach ($categories as $category_name => $minimum_amount) {
        $category_total = 0;
        foreach ($cart_items as $cart_item) {
            if (has_term($category_name, 'product_cat', $cart_item['product_id'])) {
                $category_total += $cart_item['line_total'];
            }
        }
        if ($category_total < $minimum_amount) {
            $all_thresholds_met = false;
            wc_add_notice(sprintf(__('You must add more products from the category "%s" to meet the minimum order amount of %s.', 'your-text-domain'), $category_name, wc_price($minimum_amount)), 'error');
        }
    }
    if (!$all_thresholds_met) {
        remove_action('woocommerce_checkout_order_review', 'woocommerce_checkout_payment', 20);
    }
}
// Display notice on checkout page if not all thresholds are met
add_action('woocommerce_before_checkout_form', 'display_checkout_notice_if_thresholds_not_met');
function display_checkout_notice_if_thresholds_not_met() {
    $categories = get_categories_with_minimum_amount();
    $cart = WC()->cart;
    $cart_items = $cart->get_cart();
    $notices = array();
    foreach ($categories as $category_name => $minimum_amount) {
        $category_total = 0;
        foreach ($cart_items as $cart_item) {
            if (has_term($category_name, 'product_cat', $cart_item['product_id'])) {
                $category_total += $cart_item['line_total'];
            }
        }
        if ($category_total < $minimum_amount) {
            $notices[] = sprintf(__('You have not met the minimum order amount for the category "%s". Please add more products to your cart to proceed to checkout.', 'your-text-domain'), $category_name);
        }
    }
    if (!empty($notices)) {
        wc_print_notice(implode('<br>', $notices), 'error');
        restrict_checkout_buttons();
    }
}

Comments

Add a Comment