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

自定义WooCommerce Storefront迷你购物车标题(按商品数量)

解决WooCommerce Storefront迷你购物车标题按商品数量自定义的问题

需求说明

需要根据购物车商品数量,自定义Storefront主题迷你购物车的标题文本:

  • 购物车为空:显示指定文本
  • 1件商品:显示对应专属文本
  • 2件商品:显示对应专属文本
  • 3-10件:显示带数量的专属文本
  • 10件以上:显示带数量的专属文本

原有代码问题分析

之前的实现方案存在以下致命问题:

  1. 全局使用gettext/ngettext过滤器,会替换所有页面中匹配的文本(包括购物车计数器、产品页文案等),导致功能冲突
  2. 未检查WooCommerce购物车对象是否初始化,在非Woo页面调用会触发致命错误
  3. 替换逻辑混乱,不同数量条件下同时替换单复数文本,导致显示异常

正确实现方案

使用Storefront主题专属钩子storefront_cart_link_text,仅针对迷你购物车标题修改,不会影响其他功能:

// 自定义迷你购物车标题文本
add_filter( 'storefront_cart_link_text', 'custom_storefront_minicart_title' );
function custom_storefront_minicart_title() {
    // 安全检查:确保WooCommerce购物车对象已加载
    if ( ! function_exists( 'WC' ) || ! WC()->cart ) {
        return '';
    }

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

    // 自定义各场景文本,可根据需求修改
    $texts = [
        'empty' => '购物车空空如也~',
        'one' => '1件商品在购物车',
        'two' => '2件商品待结算',
        'three_to_ten' => sprintf( '%d件商品,快来结算吧', $item_count ),
        'more_than_ten' => sprintf( '哇,%d件商品,太能买啦', $item_count )
    ];

    // 根据商品数量返回对应文本
    if ( $item_count === 0 ) {
        return $texts['empty'];
    } elseif ( $item_count === 1 ) {
        return $texts['one'];
    } elseif ( $item_count === 2 ) {
        return $texts['two'];
    } elseif ( $item_count >= 3 && $item_count <= 10 ) {
        return $texts['three_to_ten'];
    } else {
        return $texts['more_than_ten'];
    }
}

// 可选:空购物车时隐藏迷你购物车入口
add_action( 'wp_head', 'remove_empty_cart_from_menu' );
function remove_empty_cart_from_menu() {
    if ( function_exists( 'WC' ) && WC()->cart && WC()->cart->get_cart_contents_count() == 0 ) {
        remove_action( 'storefront_header', 'storefront_header_cart', 60 );
    }
}

方案优势

  1. 精准修改:仅针对Storefront迷你购物车标题,不会干扰其他WooCommerce文本
  2. 安全可靠:加入WooCommerce对象存在性检查,避免初始化错误
  3. 逻辑清晰:条件分支完全匹配需求,支持动态插入商品数量
  4. 易于维护:文本集中管理,修改时只需调整$texts数组即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 21:05:15