Halloween Sale 15% off Ends in See the plans
PHP

Minimum Combined Quantity for a Category

Requires customers to buy a minimum number of items from a category in total, for example any 6 wines, mixed as they like.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_cat_min = array(
    'categories' => array( 'wine' ), // Category slugs.
    'minimum'    => 6,               // Minimum items from these categories.
    'name'       => 'wines',         // Used in the message.
);

add_action( 'woocommerce_check_cart_items', function () use ( $wpide_cat_min ) {
    $count = 0;

    foreach ( WC()->cart->get_cart() as $item ) {
        if ( has_term( $wpide_cat_min['categories'], 'product_cat', $item['product_id'] ) ) {
            $count += (int) $item['quantity'];
        }
    }

    if ( $count > 0 && $count < $wpide_cat_min['minimum'] ) {
        wc_add_notice( sprintf( 'Please add at least %1$d %2$s to your order (you have %3$d). Mix and match as you like.', $wpide_cat_min['minimum'], esc_html( $wpide_cat_min['name'] ), $count ), 'error' );
    }
} );

Notes

Only carts that contain the category are checked, so other products can still be bought on their own.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.