我对 Woo 和 php 都很陌生,但我认为我对它有不错的掌握。我想按顺序对运费进行排序并使用 woocommerce_package_rates 挂钩。效果很好。当订单总额超过 50 美元时,我的测试网站还提供免费送货服务,我注意到我使用的免费 ups 和 usps 插件没有遵守这一点,并不断输入价格和方法,然后出现免费送货。因此,我调整了挂钩调用,只在存在免费送货时才保留该免费送货。工作起来就像一个魅力。现在我还想进行一项调整,但我无法弄清楚。我商店里有一些长度 > 24 英寸的商品。邮局对运送的物品收费太高,所以如果任何物品的长度超过 24 英寸,我想取消邮局费率(我只使用地面优势和优先权),只保留 ups 费率(或免费)运费(如果这是单一费率)。这是我正在使用的 PHP 代码,它不会计算商品长度并删除 USPS 费率(如果需要)。
add_filter( 'woocommerce_package_rates','deal_with_woocommerce_available_shipping_methods', 10, 2 );
function deal_with_woocommerce_available_shipping_methods( $rates, $package ) {
// if there are no rates don't do anything
if ( ! $rates ) {
return;
}
// get rid of rates if free is there
$rates_arr = array();
$free = false;
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->method_id ) {
$rates_arr[ $rate_id ] = $rate;
$free=true;
break;
}
}
// if it is free ship return it
if ( !empty( $rates_arr ) ) {
return $rates_arr;
}
/* remove all but ups if longest item > 24 */
if (!$free && longestItemLengthOver24()) {
foreach ( $rates as $rate_id => $rate ) {
if (strpos('UPS', serialize($rate))) {
$rates_arr[ $rate_id ] = $rate;
break;
}
}
}
// get an array of prices
$prices = array();
foreach( $rates_arr as $rate ) {
$prices[] = $rate->cost;
}
// use the prices to sort the rates
array_multisort( $prices, $rates_arr );
// return the rates
return $rates_arr;
}
function longestItemLengthOver24(){
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
$product_length = $cart_item['data']->get_length(); // Get producct length
if( ! empty($product_length) ){
if ($product_length>24) {
return true;
}
}
}
return false;
}
我尝试了上面的代码,我希望它能够计算出最长的项目,并删除除 ups 之外的所有项目(如果超过 24 英寸)。
add_filter('transient_shipping-transient-version', function($value, $name) { return false; }, 10, 2);
add_filter( 'woocommerce_package_rates' , 'deal_with_woocommerce_available_shipping_methods', 10, 2 );
function deal_with_woocommerce_available_shipping_methods( $rates, $package ) {
// if there are no rates don't do anything
if ( ! $rates ) {
return;
}
// get rid of rates if free is there
$rates_arr = array();
foreach ( $rates as $rate_id => $rate ) {
if ('free_shipping' === $rate->method_id ) {
$rates_arr[ $rate_id ] = $rate;
return $rates_arr;
}
}
$max_len = 0;
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product = $cart_item['data'];
$max_len = max($max_len, $cart_item['data']->get_length());
}
if ($max_len>24) {
foreach ( $rates as $rate_id => $rate ) {
if (!str_contains(serialize($rate),'UPS')) {
unset($rates[$rate_id]);
}
}
}
// get an array of prices
$prices = array();
foreach( $rates as $rate ) {
$prices[] = $rate->cost;
}
// use the prices to sort the rates
array_multisort( $prices, $rates );
// return the rates
return $rates;
}