Remove "proceed to checkout" button in WooCommerce after the whole quantity is greater than a certain amount

Viewed 663

Suppose someone adds 2 products to cart

  • The first product consists of 3 quantities
  • The following product consists of 2 quantities

The whole quantity is therefore equal to 5. However, I want to limit this to 4

I use the following for this, which seems to work for 1 particular product, but not for the combination of multiple products.

// Checking and validating when updating cart item quantities when products are added to cart
add_filter( 'woocommerce_update_cart_validation', 'only_six_items_allowed_cart_update', 10, 4 );
function only_six_items_allowed_cart_update( $passed, $cart_item_key, $values, $updated_quantity ) {

    $cart_items_count = WC()->cart->get_cart_contents_count();
    $original_quantity = $values['quantity'];
    $total_count = $cart_items_count - $original_quantity + $updated_quantity;

    if( $cart_items_count > 4 || $total_count > 4 ){
        // Set to false
        $passed = false;
        // Display a message
         wc_add_notice( __( "You can’t have more than 6 items in cart", "woocommerce" ), "error" );
    }
    return $passed;
}

Can someone walk me through how to do that?

1 Answers

To check the number of items during the checkout process you can use the woocommerce_check_cart_items action hook.

To remove the "proceed to checkout" button you can use remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );


Processed into a complete answer, you get: (Explanation via comment tags added in the code)

function action_woocommerce_check_cart_items() {
    // Only run in the Cart or Checkout pages
    if( is_cart() || is_checkout() ) {
        // Max allowed items
        $max_allowed = 4;
        
        // Get number of items in the cart.
        $items_in_cart = WC()->cart->get_cart_contents_count();

        // If items in cart greater than allowed amounts, show error message
        if ( $items_in_cart > $max_allowed ) {
            // Notice
            wc_add_notice( sprintf( __( 'Allowed amount is %s, You have %s items in the shopping cart', 'woocommerce' ), $max_allowed, $items_in_cart ), 'error' );
            
            // Remove proceed to checkout button
            remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
        }
    }
}   
add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10, 0 );
Related