To hide shipping methods based on product categories in WooCommerce, you can use the following code snippet. This code should be added to your theme’s functions.php
file or in a custom plugin.
/**
* Snippet Name: Hide Shipping Methods Based on Product Categories
* Snippet Author: https://wpproblog.com
*/
// Hide shipping methods based on product categories
add_filter('woocommerce_package_rates', 'hide_shipping_methods_based_on_categories', 10, 2);
function hide_shipping_methods_based_on_categories($rates, $package) {
// Define the product categories for which you want to hide shipping methods
$categories_to_hide = array('category-slug-1', 'category-slug-2');
// Get the cart contents
$cart = WC()->cart->get_cart();
// Check if any product in the cart belongs to the categories to hide
foreach ($cart as $item) {
$product = $item['data'];
$product_categories = $product->get_category_ids();
// If any product category matches the categories to hide, unset the corresponding shipping methods
if (array_intersect($product_categories, $categories_to_hide)) {
foreach ($rates as $rate_key => $rate) {
if (strpos($rate_key, 'shipping_method_to_hide_') !== false) {
unset($rates[$rate_key]);
}
}
}
}
return $rates;
}
In the code above, you need to replace ‘category-slug-1’ and ‘category-slug-2’ with the actual slugs of the product categories for which you want to hide shipping methods.
The code uses the woocommerce_package_rates filter to modify the shipping rates. It checks the product categories for each item in the cart and if any of the categories match the ones defined in the $categories_to_hide array, it removes the corresponding shipping methods from the $rates array.
Make sure to replace ‘shipping_method_to_hide_’ with the actual shipping method keys that you want to hide. You can find the shipping method keys by inspecting the HTML of the shipping method checkboxes on the checkout page.
After adding the code, the shipping methods will be hidden if any product in the cart belongs to the specified categories.
Leave a Review