2

我正在尝试编写一个函数,如果订单超过 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 :
My 25 Best WooCommerce Snippets For WordPress Part 2

4

2 回答 2

1

我知道这是一个老问题,但我有这个最近的替代方案……</p>

首先,在您的代码“如果订单超过 5 磅(80 盎司)”中, 您的if声明应该是if($whats_the_weight > 80)……!=但我认为如果您使用 WooCommerce 2.6+,您的代码有点过时了。

改为与您一起使用后global $woocommerce;$woocommerce->cart->cart_contents_weight;您可以使用: 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;
}
于 2016-07-09T10:47:28.630 回答
0

我制作了一个插件,您可以在其中设置免费送货的最大重量!

看看:http ://wordpress.org/plugins/woocommerce-advanced-free-shipping/

于 2014-05-04T16:39:08.897 回答