Dav334
Dav334

Reputation: 33

Minimum cart amount except for specific products in WooCommerce

I only permit oders with a minimum value of 15€ on my site, but want to make an exception for one product. I would really appreciated if someone knows how to help me on this. The coding for the minimum order value is below. Anyone know how I can adapt this to exclude one product via a product ID?

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

    if( is_cart() || is_checkout() ) {
        global $woocommerce;

        // Setting the minimum cart total
        $minimum_cart_total = 15;

        $total = WC()->cart->subtotal;


        if( $total <= $minimum_cart_total  ) {

            wc_add_notice( sprintf( '<strong>A Minimum of %s %s is required before checking out.</strong>'
                .'<br />Current cart\'s total: %s %s',
                $minimum_cart_total,
                get_option( 'woocommerce_currency'),
                $total,
                get_option( 'woocommerce_currency') ),
            'error' );
        }
    }
}

Upvotes: 3

Views: 750

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254378

Updated - The following code will avoid checkout under a defined minimal cart amount except for a define product ID:

add_action( 'woocommerce_check_cart_items', 'min_cart_amount' );
function min_cart_amount() {
    ## ----- Your Settings below ----- ##

    $min_amount = 15; // Minimum cart amount
    $except_ids = array(37, 53); // Except for this product(s) ID(s)

    // Loop though cart items searching for the defined product
    foreach( WC()->cart->get_cart() as $cart_item ){
        if( in_array( $cart_item['variation_id'], $except_ids ) 
        ||  in_array( $cart_item['product_id'], $except_ids )
            return; // Exit if the defined product is in cart
    }

    if( WC()->cart->subtotal < $min_amount ) {
        wc_add_notice( sprintf(
            __( "<strong>A Minimum of %s is required before checking out.</strong><br>The current cart's total is %s" ),
            wc_price( $min_amount ),
            wc_price( WC()->cart->subtotal )
        ), 'error' );
    }
}

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

enter image description here

Upvotes: 2

Related Questions