Site icon WP Beaches

Set WooCommerce cart product count total to be divisible by number

Number Of Products Woocommerce

You can set WooCommerce cart total product count to be divisible by a certain number, if it is not divisible by that number then do not allow the user to checkout.

add_action( 'woocommerce_check_cart_items', 'check_cart_items_conditionally' );
/**
 * Check cart items conditionally displaying an error notice and avoiding checkout
 * @link https://stackoverflow.com/questions/65767078/disable-woocommerce-checkout-if-cart-items-count-is-not-a-multiple-of-n
 */
function check_cart_items_conditionally() {
    $multiple_of = 6; // <= Here set the "multiple of" number if ( WC()->cart->get_cart_contents_count() % $multiple_of != 0 ) {
        wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiple_of ), 'error' );
    }
}

The divisible number in the code above is 6, using the PHP modulo operator it the cart count is not divisible by 6 the error notice is displayed and the user can’t proceed to checkout until the cart amount is fixed.

 

Cart notice

 

 

Checkout error

Exit mobile version