gpt4 book ai didi

php - Woocommerce,根据运输类别隐藏运输方式

转载 作者:可可西里 更新时间:2023-11-01 13:47:12 27 4
gpt4 key购买 nike

我试图隐藏除基于运输类别的一种运输方式之外的所有运输方式,实质上是在选择属于特定类别的产品时强制使用 FedEx 隔夜运输方式。

我从 this code 开始, 并按如下所示修改它:

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

我正在运行 Table Rate 运输模块,以及 FedEx、Purolator 和 Canada Post 模块。

最佳答案

我遇到了同样的问题,修改您的代码很有帮助。一个问题是“woocommerce_available_shipping_methods”过滤器已从 WooCommerce 2.1 中弃用。所以你必须使用新的:“woocommerce_package_rates”。有 WooCommerce tutorial也用于类似的任务。

所以,我更改了过滤器钩子(Hook),当条件为真时,我迭代所有运输方式/费率,找到我想向客户显示的那个,从中创建新数组并返回这个数组(只有一个项目) .

我认为您的问题(除了已弃用的钩子(Hook)之外)主要是错误的 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 Hook 不会每次都触发,但只有当您更改购物车中的商品或商品数量时才会触发。或者它看起来像我。也许这些可用费率以某种方式缓存在购物车内容中。

关于php - Woocommerce,根据运输类别隐藏运输方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23701467/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com