dongqiao3927 2019-03-17 22:27
浏览 45
已采纳

在Woocommerce中为两个或更多购物车商品启用免费送货

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条回答 默认 最新

  • douhui1957 2019-03-18 00:11
    关注

    There are some mistakes in your code, like missing arguments, complications and outdated things… Try the following instead:

    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;
    }
    

    This code goes in function.php file of your active child theme (or active theme). Tested and works.


    The WC_Cart method get_cart_contents_count() get the count of all items (including quantities).

    To get the count of different cart items (without including quantities), replace the line:

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

    with this one:

    $item_count = sizeof($package['contents']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?