I want to hide a set of shipping methods if a set of products are selected on WooCommerce
I think I'm almost there but I am getting an error on the unset( $rates[$method_ids] )
line.
Here's what I've got so far:
add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods_hide_many', 10, 2 );
function specific_products_shipping_methods_hide_many( $rates, $package ) {
$product_ids = array( 240555 ); // HERE set the product IDs in the array
$method_ids = array( 'flat_rate:7', 'flat_rate:13', 'flat_rate:26', 'flat_rate:27', 'local_pickup:24' ) ; // HERE set the shipping method IDs
$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_ids] );
return $rates;
}
Any advice?
CodePudding user response:
You are close, but you need to loop through $rates
and if it occurs $rate_id
, you can unset it
So you get:
function filter_woocommerce_package_rates( $rates, $package ) {
// Set the product IDs in the array
$product_ids = array( 240555, 30 );
// Set the rate IDs in the array
$rate_ids = array( 'flat_rate:7', 'flat_rate:13', 'flat_rate:26', 'flat_rate:27', 'local_pickup:24', 'local_pickup:1', 'free_shipping:2' );
// Initialize
$found = false;
// Loop through cart items checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
// Checks if a value exists in an array
if ( in_array( $cart_item['product_id'], $product_ids ) ) {
$found = true;
break;
}
}
// True
if ( $found ) {
// Loop trough
foreach ( $rates as $rate_id => $rate ) {
// Checks if a value exists in an array
if ( in_array( $rate_id, $rate_ids ) ) {
unset( $rates[$rate_id] );
}
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );