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

如何在WooCommerce库存不足错误提示中插入产品名称变量

解决方案:修改WooCommerce库存不足错误提示并添加产品名称

问题分析

你之前使用gettext过滤器失败的原因有两点:

  1. gettext过滤器的参数中没有产品对象$product_data,无法直接获取产品名称;
  2. 自定义代码存在语法错误(sprintf参数顺序错误、括号不闭合)。

原核心代码中已经提供了专门的过滤器woocommerce_cart_product_not_enough_stock_already_in_cart_message,这个钩子直接传递了产品对象、库存数量等关键参数,是修改该提示的最优方案。

替换代码

移除你之前的gettext过滤器代码,使用以下代码:

add_filter( 'woocommerce_cart_product_not_enough_stock_already_in_cart_message', 'custom_stock_error_message_with_product_name', 10, 4 );
function custom_stock_error_message_with_product_name( $message, $product_data, $stock_quantity, $stock_quantity_in_cart ) {
    // 构造包含产品名称的错误消息
    $new_message = sprintf( 
        __( 'You cannot add that amount of "%1$s" to the cart because there is not enough stock (%2$s remaining).', 'woocommerce' ),
        $product_data->get_name(),
        wc_format_stock_quantity_for_display( $stock_quantity, $product_data )
    );

    // 保留原有的"查看购物车"按钮逻辑(如果购物车页面存在)
    if ( wc_get_page_id( 'cart' ) > 0 ) {
        $wp_button_class = wc_wp_theme_get_element_class_name( 'button' ) ? ' ' . wc_wp_theme_get_element_class_name( 'button' ) : '';
        $new_message .= sprintf(
            ' <a href="%s" class="button wc-forward%s">%s</a>',
            esc_url( wc_get_cart_url() ),
            esc_attr( $wp_button_class ),
            __( 'View cart', 'woocommerce' )
        );
    }

    return $new_message;
}

代码说明

  • 直接利用钩子提供的$product_data对象,通过get_name()获取产品名称;
  • 使用wc_format_stock_quantity_for_display()格式化库存数量,和WooCommerce原生逻辑保持一致;
  • 保留了原有的"查看购物车"按钮,确保页面UI的一致性;
  • 语法完全合规,避免了之前的参数错误和括号问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 19:53:21