首页 > 解决方案 > 在 Woocommerce 中为两个或更多购物车商品启用免费送货

问题描述

在 Woocommerce 中,我想根据购物车商品的数量提供免费送货服务。首先,我开始查看可用的插件,但我找不到任何基于数量的简单解决方案。

我想要做的就是:买任何东西 2 并获得免费送货。

乱七八糟,我尝试了以下代码:

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' );

但是在将商品添加到购物车时它会挂起。从购物车中取出东西时,它也是越野车。我想在 PHP 中解决这个问题,这样我就可以进一步添加更多独特的条件,因为它们将来会出现。

有什么建议吗?

标签: phpwordpresswoocommercecartshipping-method

解决方案


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

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']);

推荐阅读