The following code snippet will easily allow you to hide certain shipping methods based on product tags. For example, you may show only free shipping for budget-buys product tag items and costly-products tag items as specified in the code.
add_filter( 'woocommerce_package_rates', 'ts_enable_shipping_based_on_tags', 10, 2 ); function ts_enable_shipping_based_on_tags( $rates, $package ) { $enabled_tags = array( 'budget-buys', 'costly-products' ); // Replace with your target tags foreach ( $rates as $rate_key => $rate ) { // Check if any cart item has a matching tag $has_matching_tag = false; foreach ( $package['contents'] as $item_key => $item ) { if ( has_term( $enabled_tags, 'product_tag', $item['product_id'] ) ) { $has_matching_tag = true; break; } } // Keep only the free shipping method if a matching tag is found if ( $has_matching_tag && 'free_shipping' !== $rate->method_id ) { unset( $rates[$rate_key] ); } } return $rates; }
Output
If the cart contains products with the “budget-buys” tag or costly-products tag, the customization will allow only the free shipping method to be available. Other shipping methods will be removed.
Instead of product tags, sometimes you may have a requirement to hide shipping for specific products. In such cases, it helps you can also hide specific shipping methods for specific shipping products in WooCommerce which will help you to optimize shipping costs.