Some products may be larger than standard size and for such products, you can offer special shipping arrangements when they go beyond a particular size. This code will disable the standard WooCommerce shipping methods for such products that have dimensions greater than the specified size.
add_filter('woocommerce_package_rates', 'ts_custom_shipping_methods', 10, 2); function ts_custom_shipping_methods($rates, $package) { // Check if any product in the cart has dimensions greater than 40*40*40 $has_large_product = false; foreach ($package['contents'] as $cart_item) { $product = wc_get_product($cart_item['product_id']); if ($product && $product->is_visible() && $product->get_length() > 40 && $product->get_width() > 40 && $product->get_height() > 40) { $has_large_product = true; break; } } // Adjust shipping methods based on the presence of large products if ($has_large_product) { // If large products are present, hide all shipping methods except free shipping $rates = ts_hide_shipping_when_free_is_available($rates); } return $rates; } // Function to hide shipping methods when free shipping is available function ts_hide_shipping_when_free_is_available($rates) { $free = array(); foreach ($rates as $rate_id => $rate) { if ('free_shipping' === $rate->get_method_id()) { $free[$rate_id] = $rate; } } return !empty($free) ? $free : $rates; }
Output
Let’s see how the dimension of a product is set from the admin side with the following steps mentioned below.
- From the WordPress admin sidebar, click on “Products”.
- Locate the product you want to set the dimensions and click on its name or “Edit” link.
- Under “Product Data” select “Shipping”, find fields for dimensions (length, width, height), enter the appropriate values, and click on Update.
When the cart contains items that are larger than the maximum dimensions specified in the code, then the code implies hiding all shipping methods except ‘free shipping’.
When the cart contains items with a product size smaller than the specified dimensions, all available shipping methods are displayed.
Similar to the above functionality, we can also hide shipping methods based on product weight. You can refer to our guide that will hide WooCommerce shipping methods for certain conditions such as weight, order total, product quantity, etc.