Looking to hide a specific shipping method on the WooCommerce cart page based on selected Product IDs? This snippet provides a solution.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
add_filter( 'woocommerce_package_rates', 'ts_specific_products_shipping_methods', 10, 2 );
function ts_specific_products_shipping_methods( $rates, $package ) {
$product_ids = array( 35 ); // HERE set the product IDs in the array
$method_id = 'flat_rate:2'; // HERE set the shipping method ID
$found = false;
// Loop through cart items Checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( in_array( $cart_item['product_id'], $product_ids ) ){
$found = true;
break;
}
}
if ( $found )
unset( $rates[$method_id] );
return $rates;
}
add_filter( 'woocommerce_package_rates', 'ts_specific_products_shipping_methods', 10, 2 );
function ts_specific_products_shipping_methods( $rates, $package ) {
$product_ids = array( 35 ); // HERE set the product IDs in the array
$method_id = 'flat_rate:2'; // HERE set the shipping method ID
$found = false;
// Loop through cart items Checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( in_array( $cart_item['product_id'], $product_ids ) ){
$found = true;
break;
}
}
if ( $found )
unset( $rates[$method_id] );
return $rates;
}
add_filter( 'woocommerce_package_rates', 'ts_specific_products_shipping_methods', 10, 2 ); function ts_specific_products_shipping_methods( $rates, $package ) { $product_ids = array( 35 ); // HERE set the product IDs in the array $method_id = 'flat_rate:2'; // HERE set the shipping method ID $found = false; // Loop through cart items Checking for defined product IDs foreach( $package['contents'] as $cart_item ) { if ( in_array( $cart_item['product_id'], $product_ids ) ){ $found = true; break; } } if ( $found ) unset( $rates[$method_id] ); return $rates; }
Output
The below output shows that the “flat rate” Shipping options are hidden based on the specific product IDs on the WooCommerce cart page.
Similarly, you can also hide the specific shipping methods based on product categories in WooCommerce cart page.