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

如何在WooCommerce产品库存信息及购物车商品前添加自定义文本

解决WooCommerce库存信息添加自定义文本的方案

嘿,我来帮你搞定这个WooCommerce库存文本的问题!你之前用woocommerce_cart_item_price处理价格前缀的思路完全没问题,针对库存信息,咱们分单个产品页面和购物车两个场景来实现:

1. 单个产品页面:在库存状态前加自定义文本

单个产品页面的库存状态(比如“有货”“缺货”)是通过woocommerce_get_stock_html这个过滤器来控制的,咱们直接用它来插入自定义文本就行。示例代码如下:

add_filter('woocommerce_get_stock_html', 'add_custom_text_before_stock_single_product', 10, 2);
function add_custom_text_before_stock_single_product($stock_html, $product) {
    // 这里替换成你想要的自定义文本
    $custom_text = '<span class="custom-stock-label">库存状态:</span>';
    // 把自定义文本拼接到原有库存信息的前面
    return $custom_text . $stock_html;
}

2. 购物车商品:显示带自定义文本的库存信息

购物车默认不会主动显示库存状态,所以咱们需要把库存信息添加到购物车项目里。这里有两种常用的实现方式:

方式一:在购物车商品的附加信息区显示

用woocommerce_get_item_data过滤器,能把库存信息加到商品的附加数据区域(比如规格信息下面):

add_filter('woocommerce_get_item_data', 'add_custom_stock_info_to_cart_items', 10, 2);
function add_custom_stock_info_to_cart_items($item_data, $cart_item) {
    $product = $cart_item['data'];
    // 对简单产品和可变产品的变体生效,可根据需求调整
    if ($product->is_type('simple') || $product->is_type('variation')) {
        $stock_status = $product->get_stock_status();
        // 把英文库存状态转为中文,可按需修改
        $stock_text = $stock_status === 'instock' ? '有货' : '缺货';
        // 拼接自定义文本和库存状态
        $item_data[] = array(
            'key'     => '库存状态',
            'value'   => $stock_text,
            'display' => '<span class="custom-cart-stock">库存状态:' . $stock_text . '</span>'
        );
    }
    return $item_data;
}

方式二:在商品名称后面直接显示

如果想让库存信息更靠近商品名称,可以用woocommerce_cart_item_after_product_name动作钩子:

add_action('woocommerce_cart_item_after_product_name', 'add_stock_text_after_cart_product_name', 10, 2);
function add_stock_text_after_cart_product_name($cart_item, $cart_item_key) {
    $product = $cart_item['data'];
    $stock_status = $product->get_stock_status();
    $stock_text = $stock_status === 'instock' ? '有货' : '缺货';
    // 输出带自定义文本的库存信息
    echo '<br><span class="custom-cart-stock-label">库存状态:' . $stock_text . '</span>';
}

小提示

  • 把这些代码添加到你的主题functions.php文件,或者用专门的自定义代码插件(比如Code Snippets)来添加,避免主题更新后代码丢失。
  • 你可以通过CSS调整.custom-stock-label、.custom-cart-stock这些类的样式,让文本更符合你的店铺风格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:16:23