You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce仅贴纸品类满5件免运费代码调整需求

解决WooCommerce仅纯贴纸品类满5件免运费的问题

原代码的问题在于只统计了贴纸商品的数量,未校验购物车中是否存在其他品类商品,导致混合商品时仍会触发免运费。以下是调整后的代码:

function filter_woocommerce_shipping_free_shipping_is_available( $is_available, $package, $shipping_method ) {
   
    /* SETTINGS free shipping TOTEBAG ONLY */
    // Set categories
    $specific_categories = array( 'stickers' );
    
    // Set minimum
    $minimum = 5;
    
    /* END settings */

    // Counter
    $count = 0;
    // 标记是否存在非贴纸品类商品
    $has_non_sticker_items = false;
    
    // Loop through cart items
    foreach( $package['contents'] as $cart_item ) {
        $product_id = $cart_item['product_id'];
        // 检查当前商品是否属于贴纸品类
        if ( has_term( $specific_categories, 'product_cat', $product_id ) ) {
            $count += $cart_item['quantity'];
        } else {
            // 存在非贴纸商品,标记为true
            $has_non_sticker_items = true;
        }
    }
    
    // Condition:仅当贴纸数量达标且无其他品类商品时,才启用免运费
    if ( $count >= $minimum && !$has_non_sticker_items ) {
        $notice = __( 'Free Shipping', 'woocommerce' );
        $is_available = true;   
    } else {
        $notice = __( 'NO Free Shipping', 'woocommerce' );
        $is_available = false;      
    }
    
    // Display notice
    if ( isset( $notice ) ) {
        wc_add_notice( $notice, 'notice' );
    }
 
    // Return
    return $is_available;
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'filter_woocommerce_shipping_free_shipping_is_available', 10, 3 );

关键修改说明:

  • 新增$has_non_sticker_items变量,用于追踪购物车中是否存在非贴纸品类的商品
  • 在循环遍历购物车商品时,若检测到不属于贴纸品类的商品,立即将$has_non_sticker_items设为true
  • 修改最终判断条件:只有当贴纸商品数量≥5 且 购物车中没有其他品类商品时,才允许免运费

内容的提问来源于stack exchange,提问作者Cel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 03:12:12