Exclude a shipping method if the cart contains certain products or product categories.
A client asked that a particular shipping method be hidden when certain bulky items were in the customer’s cart.
Inspiration from businessbloomer.com
Rodolfo Melogli of BusinessBloomer.com has an extensive library of posts with code snippets for WooCommerce. I read through a few of those related to shipping to get the direction I needed for the code below – the ‘
Find shipping rate array key
Rodolfo’s post shows how to find the shipping method ID, by looking at the source code of the cart page. This may be too difficult for non-developers so I wrote code to find the ID based on the method name (even though this post is aimed at developers).
The code goes through the rates, retrieves the readable name (as entered when the shipping method was created) and checks the name in the code. The code here searches for text (“An Post“) within the readable name (“An Post various rates“) rather than an exact match as the name could be inadvertently changed by the site admin e.g. remove the ‘various rates‘ part.
I think that this searching makes the code more readable and easier to maintain. In the client site the shipping method ID is
betrs_shipping:2-1 (from a Table Rate Shipping plugin by Bolder Elements) – that method ID won’t make any sense when reviewing the code in 6 months time.
Specify product IDs and categories
Next the code looks up an array of product IDs to see if any are in the cart.
If none of these products are in the cart the code goes through the cart again, examining the categories of each product. This is done as a separate loop because it calls
get_the_terms() for each cart item and it’s best to have found a matching product ID and skipped this loop if possible.
Rodolfo’s equivalent of this plugin uses the product’s shipping class to disable a shipping method. While that code is shorter and allows the shop manager add products to the exclusion list, my client is not very technical and may forget to add it or have difficulty remembering where to set the shipping class.