我在我的WooCommerce商店里有一些产品很重(超过20公斤),需要通过某种运输方式运输。我想隐藏“装运方法\u 0 \u统一费率2”
,用于所有包含超过20公斤产品的购物车项目。
我试图调整下面的片段,但它不完整和工作:
add_filter( 'woocommerce_package_rates', 'hide_shipping_based_on_tag' , 10, 1 );
function check_cart_for_share() {
// specify the product id's you want to hide
$product_ID = array(
'113', // Product name
);
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
// loop through the array looking for the products. Switch to true if the product 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, $product_ID ) ) {
$found = true;
break;
}
}
}
return $found;
}
function hide_shipping_based_on_tag( $available_methods ) {
// use the function above to check the cart for the products.
if ( check_cart_for_share() ) {
// remove the method you want
unset( $available_methods['shipping_method_0_flat_rate2'] ); // Replace with the shipping option that you want to remove.
}
// return the available methods without the one you unset.
return $available_methods;
}
感谢您的帮助。
您正在使代码中的内容变得更加复杂,并且您的配送方法ID不是一个好的ID…请尝试以下方法:
add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {
$product_ids = array( 113 ); // HERE set the product IDs in the array
$method_id = 'flat_rate:2'; // HERE set the shipping method ID
$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_id] );
return $rates;
}
代码进入函数。活动子主题(或活动主题)的php文件。测试和工作。
您应该需要刷新发货缓存:
1)首先,此代码已保存在您的函数中。php文件
2)在配送设置中,输入配送区域并禁用配送方法并“保存”。然后重新启用该装运方法并“保存”。你完了