Set a minimum order value for except for product tags in WooCommerce

Viewed 250

I currently have a wordpress site with a minimum order value set for my WooCommerce store, set up in my functions.php and it works perfectly. I now want to set one product tag as an exception to this rule, and have no minimum order value for this... is this possible?

I am actually using Set a minimum order amount in WooCommerce answer code.

Not sure whether changing to a plug-in such as ‘wc minimum order amount’ is the answer or can this be added in the existing code?

Any advice greatly appreciated!

1 Answers

To make this code non active for specific product tags, use the following:

add_action( 'woocommerce_check_cart_items', 'required_min_cart_subtotal_amount' );
function required_min_cart_subtotal_amount() {

    $minimum_amount = 35; // HERE Set minimum cart total amount
    $product_tags   = array('Lewis'); // HERE set the product tags (term names, slugs or Ids)
    $cart_subtotal  = WC()->cart->subtotal; // Total (before taxes and shipping charges)
    $tag_found      = false;
    
    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // Check for product tag
        if( has_term( $product_tags, 'product_tag', $cart_item['product_id'] ) ) {
            $tag_found = true;
            break;
        }
    }

    // Add an error notice is cart total is less than the minimum required
    if( $cart_subtotal < $minimum_amount && ! $tag_found ) {
        // Display an error message
        wc_add_notice( '<strong>' . sprintf( __("A minimum total purchase amount of %s is required to checkout."), wc_price($minimum_amount) ) . '<strong>', 'error' );
    }
}

Or if you want to exclude specific product tags from cart subtotal use instead:

add_action( 'woocommerce_check_cart_items', 'required_min_cart_subtotal_amount' );
function required_min_cart_subtotal_amount() {

    $minimum_amount = 35; // HERE Set minimum cart total amount
    $product_tags   = array('Disc'); // HERE set the product tags (term names, slugs or Ids)
    $cart_subtotal  = 0; // Total (before taxes and shipping charges)

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // Check for product tag
        if( ! has_term( $product_tags, 'product_tag', $cart_item['product_id'] ) ) {
            $cart_subtotal += $cart_item['line_subtotal'] + $cart_item['line_subtotal_tax'];
        }
    }

    // Add an error notice is cart total is less than the minimum required
    if( $cart_subtotal < $minimum_amount ) {
        // Display an error message
        wc_add_notice( '<strong>' . sprintf( __("A minimum total purchase amount of %s is required to checkout."), wc_price($minimum_amount) ) . '<strong>', 'error' );
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Related