按产品类别隐藏运输方式,如果没有,则隐藏



如果购物车中有成品类别,我试图组合一个函数来隐藏运输方法,如果该类别不在购物车中,则隐藏另一个。这是我能够组合的功能,但它不起作用。你能帮我吗?

function product_category_find_id_in_cart() {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
if ( has_term( 'hangers', 'product_cat', $cart_item['product_id'] ) ) {
unset( $rates['free_shipping1'] );
}
else {
unset( $rates['flat_rate:6'] );
}
return $rates;
}
}

我需要它也适用于各种运输方式,而不仅仅是隐藏一种。非常感谢。

感谢@7uc1f3r,如果产品属于某个类别,我有一个新的代码可以隐藏运输方法,但如果产品不属于该类别,我需要隐藏其他运输方法。这将是新的配方,感谢@LoicTheAztec:

add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {
// HERE set the product category in the array (ID, slug or name)
$terms = array( 'hangers' ); 
$taxonomy = 'product_cat'; 
// HERE set the shipping methods to be removed (like "fat_rate:5")
$method_instances_ids = array('1');  
$found = false;
// Loop through cart items checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( has_term( $terms, $taxonomy, $cart_item['product_id'] ) ){
$found = true;
break;
}
}
if ( ! $found ) return $rates; // If not found we exit
// Loop through your active shipping methods
foreach( $rates as $rate_id => $rate ) {
// Remove all other shipping methods other than your defined shipping method
if ( in_array( $rate_id, $method_instances_ids ) ){
unset( $rates[$rate_id] );
}
}    
return $rates;
}

我找到了!!

add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {
// HERE set the product category in the array (ID, slug or name)
$terms = array( 'hangers' ); 
$taxonomy = 'product_cat'; 
// HERE set the shipping methods to be removed (like "fat_rate:5")
$method_instances_ids = array('flat_rate:12','flat_rate:13','flat_rate:14');  
$found = false;
// Loop through cart items checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( has_term( $terms, $taxonomy, $cart_item['product_id'] ) ){
$found = true;
break;
}
}
if ( ! $found ) { unset( $rates['flat_rate:6'],$rates['flat_rate:7'],$rates['flat_rate:8'],$rates['flat_rate:9'],$rates['flat_rate:10'],$rates['flat_rate:11'] ); return $rates;} // If not found we exit
else {
// Loop through your active shipping methods
foreach( $rates as $rate_id => $rate ) {
// Remove all other shipping methods other than your defined shipping method
if ( in_array( $rate_id, $method_instances_ids ) ){
unset( $rates[$rate_id] );
}
}    
return $rates;
}}

最新更新