Set an upper or lower weight limit for the shopping cart and prevent checkout.
Reader Kyle commented on my ‘Change no shipping methods available message‘ post asking if different messages could be displayed for different situations.
Of course this is possible and the sample code in the post demonstrated this.
Checking Weight
We exchanged a few emails and Kyle explained that he was looking to limit the cart weight because his carrier had an upper weight limit. I explained that the ‘woocommerce_no_shipping_available_html’ filter would not be useful here as it only displays a message and would not prevent the checkout process from continuing. Furthermore, it may not be triggered if the user’s address has available shipping methods.
I did a quick search and found a short post on the very topic: How To Set Purchase Limits On Your WooCommerce Cart. It has code for minimum weight and minimum money amounts for the cart.
Set Minimum Cart Weight
I adapted the minimum weight snippet, removing the unnecessary reference to the global $woocommerce variable and changing the legacy ‘cart_contents_weight’ member variable to the get_cart_contents_weight() function. I also removed the is_cart() and is_checkout() checks because the do_action() call only runs on those pages and hence the checks are unnecessary.
Checkout Blocked
The beauty of using wc_add_notice() with ‘error’ status is that it blocks checkout!
The cart page will show the error message and allow you to proceed to the checkout.
The checkout page will display the same message and a WooCommerce message directing customers back to the cart.
Set Maximum Cart Weight
This code is very similar to the minimum cart weight snippet, with just a change in the calculation and the error message text.
Thank you so much for this! :)
Hi Damien, first: Thank you for posting that solution. It’s really helpful for individual requirements. I have an extended question: Do you also have an idea how weight can be used to set minimum levels? So the purchase is only possible with at least 6kg increments. The cart has to be always at 6kg, 12kg, 18kg etc. to make a purchase possible. THX for your help! Martin
I would use division and modulus operators you can see if a number is evenly divisible by 6 and is at least 6.
Change line 19 from
if( $cart_contents_weight > $maximum_weight ) {
to
$increments = 6; $min_weight = 6; if ( ( $weight % $increments != 0 ) || ( $weight / $min_weight <= 0 ) ) {
Here’s the full code: https://gist.github.com/damiencarbery/89c74306b79bca6b83466939517fa518
The important line is:
if ( ( $cart_contents_weight % $increments != 0 ) || ( $cart_contents_weight / $minimum_weight < 0 ) ) {