Limit the number of cart items in Woocommerce

// Allowing adding only one unique item to cart and displaying an error message
add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_validation', 10, 1 );
function add_to_cart_validation( $passed ) {
    if( ! WC()->cart->is_empty() ){
        wc_add_notice( __("You can add only one item to cart", "woocommerce" ), 'error' );
        $passed = false;
    }
    return $passed;
}

// Avoiding checkout when there is more than one item and displaying an error message
add_action( 'woocommerce_check_cart_items', 'check_cart_items' ); // Cart and Checkout
function check_cart_items() {
    if( sizeof( WC()->cart->get_cart() ) > 1 ){
        // Display an error message
        wc_add_notice( __("More than one items in cart is not allowed to checkout", "woocommece"), 'error' );
    }
}

Leave a Reply

Your email address will not be published.