I need help in woocommerce shipping options, I want to hide flat rate for a particular product category, where I only want to show local delivery or local pickup options.
For all others categories all options should work.
I have try to do it with that code (added in function.php file of my theme):
function cart_has_product_with_orange_cats() {
global $woocommerce;
$product_in_cart = false;
// start of the loop that fetches the cart items
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_cat' );
// second level loop search, in case some items have several categories
if($terms){
foreach ($terms as $term) {
$_categoryid = $term->term_id;
if ( $_categoryid == 16 ) {
//category is in cart!
$product_in_cart = true;
}
}
}
}
return $product_in_cart;
}
// add filter and function to hide method
add_filter( 'woocommerce_available_shipping_methods', 'custom_shipping_methods' , 10, 1 );
function custom_shipping_methods( $available_methods ){
if ( cart_has_product_with_orange_cats() ) {
foreach($available_methods as $key => $method){
if( $key == 'local_delivery' || $key == 'local_pickup'){
continue;
}
unset($available_methods[$key]);
}
// remove the rate you want
}
// return the available methods without the one you unset.
return $available_methods;
}
But it isn't working for me, maybe because outdated code for latest WooCommerce version or any other issue.
How can I achieve this?
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…