WooCommerce hide shipping method based on category advanced

I sell bicycles and parts. If someone buys a bicycle in the WooCommerce webshop only the shipping method ‘local_pickup’ should be visible. If someone buys a part only ‘flat_rate’ (shipping) should be available. If someone buys a bicylce and and a part only shipping method ‘local_pickup’ should be available. How should I solve this challenge with a new code snippet?

I have two snippets that work perfectly, but only do one part of the job…

Read More
 // Hide 'Shipping' (flat_rate) with a bicylce in the shopping cart
add_filter( 'woocommerce_package_rates', 'hide_shipping_based_on_tag' ,    10, 1 );

function check_cart_for_share() {

// specify the category id's you want to hide flat_rate
$category_ID = array(
'7', // Type A bike
'8', // Type B bike
'9', // Type c bike
'10', // Type D bike

);
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;

$found = false;

// loop through the array looking for the categories. Switch to true if the category is found.
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 ) ) {

    $found = true;
    break;
}
}
}

return $found;

}

function hide_shipping_based_on_tag( $available_methods ) {

// use the function above to check the cart for the categories.
if ( check_cart_for_share() ) {

// remove the method you want
unset( $available_methods['flat_rate'] ); // Replace "flat_rate" with the shipping option that you want to remove.
  }

// return the available methods without the one you unset.
return $available_methods;

  }

and

 // Hide local ickup (local_pickup) with parts in shopping cart
 add_filter( 'woocommerce_package_rates', 'hide_shipping_based_on_tag' ,    10, 1 );

 function check_cart_for_share() {

// specify the category id's you want to hide flat_rate
$category_ID = array(
'11', // Parts

);
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;

$found = false;

// loop through the array looking for the categories. Switch to true if the category is found.
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 ) ) {

    $found = true;
    break;
}
}
}

 return $found;

 }

 function hide_shipping_based_on_tag( $available_methods ) {

// use the function above to check the cart for the categories.
if ( check_cart_for_share() ) {

// remove the method you want
unset( $available_methods['local_pickup'] ); // Replace "local_pickup" with the shipping option that you want to remove.
  }

// return the available methods without the one you unset.
return $available_methods;

   }

With kind regards,

Sjors

Related posts