我在woocommerce中有两种运输方式,固定费用标准(方法1)和固定费用特快专递(方法2)。 X和Z这两个产品类别只能使用方法1,因此,如果购物车中包含X或Z类别的任何商品,我想在结帐时从运输选择中隐藏方法2。
我搜索了Stackoverflow,找到了该帖子Hide specific shipping method for specific products in Woocommerce,并尝试套用答案,但未成功。我尝试过的代码以及我认为适当的修改如下。
function specific_products_shipping_methods( $rates, $package ) { $product_ids = array( 39 ); // HERE set the product IDs in the array $method_id = 'Express_Post:5'; // 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; }
发货方式2的ID为5,产品类别X的ID为39。我禁用,保存,启用和保存了运输方法2。将上述内容作为代码段添加到php文件时,它破坏了网站(“您的网站遇到技术难题”),或者在输入运输地址后,我将被卡住(飞轮),因此无法上车检查代码是否有效。
[更新]
非常感谢@Kelvin Mariano的回复。为了避免出错,我多次尝试了几种不同的代码。我不再遇到任何错误,但是即使购物车中有不合格的物品,两种运输方式仍然会出现。
相关运送方法的回显输出为:
[flat_rate:5] => WC_Shipping_Rate Object ( [data:protected] => Array (` [id] => flat_rate:5 [method_id] => flat_rate [instance_id] => 5 [label] => Express Post
我尝试的代码是这样:
function bz_specific_products_shipping_methods( $rates, $package ) { $product_ids = array( 39 ); // HERE set the product IDs in the array //$method_id = 'flat_rate:5'; // HERE set the shipping method ID $method_id = 'flat_rate:5'; // HERE set the shipping method ID $found = false; /* //please remove this comment to view all shipping methods and their information `echo "<pre>"; print_r( $rates ); echo "</pre>"; exit();*/` // 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 ){ if( isset( $rates[$method_id] ) ){ unset( $rates[$method_id] ); } } return $rates; } //use the filter this is important add_filter( 'woocommerce_package_rates','bz_specific_products_shipping_methods', 10, 2 );
更新2
Array
(
[flat_rate:1] => WC_Shipping_Rate Object
(
[data:protected] => Array
(
[id] => flat_rate:1
[method_id] => flat_rate
[instance_id] => 1
[label] => Flat rate Standard
[cost] => 9.00
)
)
[flat_rate:5] => WC_Shipping_Rate Object
(
[data:protected] => Array
(
[id] => flat_rate:5
[method_id] => flat_rate
[instance_id] => 5
[label] => Express Post
[cost] => 11.77
我在woocommerce中有两种运输方式,固定费用标准(方法1)和固定费用特快专递(方法2)。 X和Z这两个产品类别只能使用方法1,因此我想从...
我做了两个重要的更改,更改了函数的名称以避免冲突,并更改了要为特定测试删除的方法。
我发现上面的代码正在干扰插件WooCommerce Advanced Free Shipping的操作。我停用了该插件并删除了上面的代码。然后,我安装了适用于Woocommerce的Advanced Flat Rate Shipping,该插件允许我设置参数,以防止这两个产品类别适用于运输方法2。