我试图编写一个函数,如果订单超过5磅(80盎司),则仅提供免费送货(删除所有其他选项),但它不工作,尽管代码似乎正确。
这是我的:
// Hide ALL shipping options but FREe when over 80 ounches (5 pounds)
add_filter( 'woocommerce_available_shipping_methods', 'ship_free_if_over_five_pounds' , 10, 1 );
/**
* Hide ALL Shipping option but free if over 5 pounds
*
* @param array $available_methods
*/
function ship_free_if_over_five_pounds( $available_methods ) {
global $woocommerce;
$whats_the_weight = $woocommerce->cart->cart_contents_weight;
if($whats_the_weight != 80) :
// Get Free Shipping array into a new array
$freeshipping = array();
$freeshipping = $available_methods['free_shipping'];
// Empty the $available_methods array
unset( $available_methods );
// Add Free Shipping back into $avaialble_methods
$available_methods = array();
$available_methods[] = $freeshipping;
endif;
return $available_methods;
}
任何想法吗?
代码是基于示例#19在这个网站上:
我的25个最好的WooCommerce片段WordPress Part 2
我知道这是一个老问题,但我最近有这个选择…
首先,在代码中"如果订单超过5磅(80盎司)"你的 if
语句应该是 if($whats_the_weight > 80)
而不是 !=
.但是我认为你的代码有点过时,如果你使用WooCommerce 2.6+。
在使用$woocommerce->cart->cart_contents_weight;
代替global $woocommerce;
之后,您可以使用: WC()->cart->cart_contents_weight;
我有这个更近期的代码片段基于这个官方线程WooCommerce 2.6+。你应该试试:
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );
function my_hide_shipping_when_free_is_available( $rates ) {
$cart_weight = WC()->cart->cart_contents_weight; // Cart total weight
$free = array();
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->method_id && $cart_weight > 80 ) { // <= your weight condition
$free[ $rate_id ] = $rate;
break;
}
}
return ! empty( $free ) ? $free : $rates;
}
对于WooCommerce 2.5,你应该试试这个:
add_filter( 'woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2 );
function hide_shipping_when_free_is_available( $rates, $package ) {
$cart_weight = WC()->cart->cart_contents_weight; // Cart total weight
// Only modify rates if free_shipping is present
if ( isset( $rates['free_shipping'] ) && $cart_weight > 80 ) { // Here your weight condition
// To unset a single rate/method, do the following. This example unsets flat_rate shipping
unset( $rates['flat_rate'] );
// To unset all methods except for free_shipping, do the following
$free_shipping = $rates['free_shipping'];
$rates = array();
$rates['free_shipping'] = $free_shipping;
}
return $rates;
}
我做了一个插件,你可以设置免费送货的最大重量!
请看:http://wordpress.org/plugins/woocommerce-advanced-free-shipping/