I am trying to disabel/hide a shipping method based on a category in Woocommerce (2.1.12).
I successfully achieved hiding a paymeny method using this function:
function filter_gateways($gateways){
$category_ID = array('14'); // <----------- add the ids for which u want to turn off "cash on delivery"
global $woocommerce;
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
$terms = get_the_terms( $values['product_id'], 'product_cat' );
foreach ($terms as $term) {
if( in_array( $term->term_id, $category_ID ) ) {
unset($gateways['cod']);
break;
}
break;
}
}
return $gateways;
}
add_filter('woocommerce_available_payment_gateways','filter_gateways');
However, disabling a shipping method seems not to be working. I tried three different snippets.
No.1 (not working):
function custom_shipping_methods( $available_methods ) {
$category_ID = array('14'); // <----------- add the ids for which u want to turn off "local pickup"
global $woocommerce;
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
$terms = get_the_terms( $values['product_id'], 'product_cat' );
foreach ($terms as $term) {
if( in_array( $term->term_id, $category_ID ) ) {
unset( $available_methods['local_pickup'] );
break;
}
break;
}
}
return $available_methods;
}
add_filter( 'woocommerce_available_shipping_methods', 'custom_shipping_methods' );
No.2 (not working):
function custom_shipping_methods( $is_available ) {
$category_ID = array('14'); // <----------- add the ids for which u want to turn off "local pickup"
global $woocommerce;
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
$terms = get_the_terms( $values['product_id'], 'product_cat' );
foreach ($terms as $term) {
if( in_array( $term->term_id, $category_ID ) ) {
$is_available = false;
break;
}
break;
}
}
return $is_available;
}
add_filter( 'woocommerce_shipping_local_pickup_is_available', 'custom_shipping_methods' );
No.3 (not working) I tried this because apparently newer versions of woocommerce use the filter below:
function hide_local_pickup( $rates, $package ) {
$category_ID = array('14'); // <----------- add the ids for which u want to turn off "local pickup"
global $woocommerce;
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
$terms = get_the_terms( $values['product_id'], 'product_cat' );
foreach ($terms as $term) {
if( in_array( $term->term_id, $category_ID ) ) {
unset( $rates['local_pickup'] );
break;
}
break;
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_local_pickup' , 10, 2 );