John Davidson

php - Hide multiple shipping methods based on product IDs in WooCommerce

0 comments
Message:


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?



My Answer:
The issue with your code is that you are trying to unset an array of method IDs ($method_ids) from the $rates array, which is not the correct way to do it. Instead, you should loop through the $rates array and unset each individual method ID if it matches any of the IDs in your $method_ids array.

Here's the corrected code:

php
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;
}
}

// Loop through shipping rates and unset if method ID matches
foreach( $rates as $rate_key => $rate ) {
if ( in_array( $rate->get_id(), $method_ids ) ) {
unset( $rates[$rate_key] );
}
}

return $rates;
}


This code should now correctly loop through the $rates array and unset any shipping methods that match the IDs in your $method_ids array.

Rate this post

4 of 5 based on 9027 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us