Enable free shipping for two or more cart items in Woocommerce

时间:2019-03-17 22:27:59

标签: php wordpress woocommerce cart shipping-method

In Woocommerce, I want to offer free shipping based on the number of cart items. First, I began looking at the available plugins and I can't find any simple solution based on quantity.

All I want to do is: buy 2 of anything and get free shipping.

Messing around, I tried the following code:

function free_ship( $is_available ) {
    $count = 0;
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    foreach($items as $item) {
        $count++;
    }
    echo $count;

    if ( $count == 1 ) {
        echo 'add one more for free shipping';
        return $is_available;
    } elseif ($count > 1) {
        echo 'you get free shipping';
        return false;
    } else {
        echo 'nothing in your cart';
        return $is_available;
    }
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'free_ship' );

But it hangs when adding items to the cart. It also is buggy when removing things from the cart. I'd like to figure this out in PHP, so that I can further add more unique conditions in they happen to pop up in the future.

Have any suggestions?

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些错误,例如缺少参数,复杂性和过时的东西……请尝试以下操作:

add_filter( 'woocommerce_shipping_free_shipping_is_available', 'free_shipping_for_x_cart_items', 10, 3 );
function free_shipping_for_x_cart_items( $is_available, $package, $shipping_method ) {
    $item_count = WC()->cart->get_cart_contents_count();

    if ( $item_count == 1 ) {
        $notice = __("Add one more for free shipping");
        $is_available = false;
    } elseif ($item_count > 1) {
        $notice = __("You get free shipping");
        $is_available = true;
    }

    if ( isset($notice) ) {
        wc_add_notice( $notice, 'notice' );
    }
    return $is_available;
}

此代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。


WC_Cart方法get_cart_contents_count()获取所有(包括数量)的项目的计数。

要获取不同购物车商品的数量 (不包括数量),请替换行:

$item_count = WC()->cart->get_cart_contents_count();

与此:

$item_count = sizeof($package['contents']);