在 WooCommerce 中更改添加到购物车库存错误通知

Change add to cart stock error notice in WooCommerce

当客户尝试将过多的商品添加到购物车时,他们会看到此错误通知:

You cannot add that amount to the cart - we have X in stock and you already have Y in your cart.

此行为包含在 WC_Cart add_to_cart() method source code at line 1067

我想隐藏库存详细信息并将其替换为:

You cannot add that amount to the cart — we don't have enough in stock.

如何在不覆盖源代码的情况下更改 WooCommerce 中的添加到购物车库存错误通知?

借助 "Say What" 插件,您可以在不修改插件文件的情况下更改上述文本。按照以下步骤更改文本:

  1. 安装Say What插件

  2. 访问工具 > 文本更改

  3. 单击添加新

  4. 根据需要填写字段,例如

    • 原始字符串: You cannot add that amount to the cart — we have %1$s in stock and you already have %2$s in your cart.
    • 文本域: woocommerce
    • 文本上下文:
    • 替换字符串: You cannot add that amount to the cart — we don't have enough in stock.
  5. 单击添加 按钮保存更改。

可以这样在自定义挂钩函数中使用 gettext 过滤器挂钩:

add_filter( 'gettext', 'custom_add_to_cart_stock_error_notice', 10, 3 );
function custom_add_to_cart_stock_error_notice( $translated, $text, $domain ) {

    if ( $text === 'You cannot add that amount to the cart — we have %1$s in stock and you already have %2$s in your cart.' && 'woocommerce' === $domain ) {
        $translated = __("You cannot add that amount to the cart — we don't have enough in stock.", $domain );
    }

    return $translated;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

请注意,@loictheaztec 的代码有效,但如果要使用数量,则需要将第四行中的引号更改为单引号

    add_filter( 'gettext', 'custom_add_to_cart_stock_error_notice', 10, 3 );
function custom_add_to_cart_stock_error_notice( $translated, $text, $domain ) {

    if ( $text === 'You cannot add that amount to the cart — we have %1$s in stock and you already have %2$s in your cart.' && 'woocommerce' === $domain ) {
        $translated = __('You cannot add that to the cart — we have %1$s in stock and you already have %2$s in your cart.', $domain );
    }