我试图根据运输类别隐藏除一种运输方法之外的所有运输方法,本质上是在选择属于特定类别的产品时强制使用 FedEx 隔夜方法。
我从这段代码,并将其修改如下:
add_filter( 'woocommerce_available_shipping_methods', 'hide_shipping_based_on_class' , 10, 1 );
function check_cart_for_share() {
// load the contents of the cart into an array.
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
// loop through the array looking for the tag you set. Switch to true if the tag is found.
foreach ($cart as $array_item) {
$term_list = wp_get_post_terms( $array_item['product_id'], 'product_shipping_class', array( "fields" => "names" ) );
if (in_array("Frozen",$term_list)) {
$found = true;
break;
}
}
return $found;
}
function hide_shipping_based_on_class( $available_methods ) {
// use the function above to check the cart for the tag.
if ( check_cart_for_share() ) {
// remove the rate you want
unset( $available_methods['canada_post,purolator,fedex:FEDEX_GROUND,fedex:GOUND_HOME_DELIVERY'] );
}
// return the available methods without the one you unset.
return $available_methods;
}
但它似乎并没有隐藏任何运输方式。不知道我错过了什么......
这是一个多站点安装,我正在加拿大一侧进行测试http://stjeans.harbourcitydevelopment.com
我正在运行表费率运输模块以及 FedEx、Purolator 和加拿大邮政模块。
我遇到了同样的问题,修改你的代码有帮助。一个问题是“woocommerce_available_shipping_methods“ WooCommerce 2.1 中已弃用过滤器。因此您必须使用新过滤器:”woocommerce_package_rates“。 有WooCommerce 教程也用于类似的任务。
因此,我更改了过滤器挂钩,当条件为真时,我迭代所有运输方式/费率,找到我想要向客户显示的运输方式/费率,从中创建新数组并返回该数组(仅包含一项)。
我认为你的问题(除了已弃用的钩子之外)主要是在错误的 unset($available_methods[...]) 行中。它不能那样工作。
这是我的代码:
add_filter( 'woocommerce_package_rates', 'hide_shipping_based_on_class' , 10, 2 );
function hide_shipping_based_on_class( $available_methods ) {
if ( check_cart_for_share() ) {
foreach($available_methods as $key=>$method) {
if( strpos($key,'YOUR_METHOD_KEY') !== FALSE ) {
$new_rates = array();
$new_rates[$key] = $method;
return $new_rates;
}
}
}
return $available_methods;
}
警告!我发现 woocommerce_package_rates 挂钩并不是每次都被解雇,但仅当您更改购物车中的商品或商品数量时。或者对我来说看起来就是这样。也许这些可用的价格以某种方式缓存在购物车内容中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)