Sea*_*nns 5 php wordpress fedex shipping woocommerce
我试图隐藏基于货运类的所有货运方法,当选择属于特定类的产品时,基本上强制采用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;
}
Run Code Online (Sandbox Code Playgroud)
它似乎并没有隐藏任何运输方法.不确定我错过了什么......
这是一个多站点安装,我正在加拿大一侧测试它http://stjeans.harbourcitydevelopment.com
我正在运行Table Rate运输模块,以及FedEx,Purolator和Canada Post模块.
我遇到了同样的问题并且帮助了你的代码.一个问题是WooCommerce 2.1不推荐使用" woocommerce_available_shipping_methods "过滤器.所以你必须使用新的:" woocommerce_package_rates ".也有类似任务的WooCommerce教程.
因此,我更改了过滤器挂钩,当条件为真时,我迭代所有送货方法/费率,找到我想要显示给客户的那个,从中创建新数组并返回该数组(只有一个项目).
我认为你的问题是(除了弃用的钩子)主要是错误的未设置($ 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;
}
Run Code Online (Sandbox Code Playgroud)
警告!我发现每次都不会触发 woocommerce_package_rates钩子,但只有当您更改购物车中的物品或物品数量时才会触发.或者它看起来像我.也许那些可用的费率以某种方式缓存购物车内容.