首页 > 解决方案 > 如何在 WooCommerce 4.5+ 中编辑“库存不足”或“购物车中库存不足”消息

问题描述

在我的 Woocommerce 商店中,当我尝试在我的购物篮中添加比我们库存更多的商品时(即,如果我们有 9 个,则为 10 个)我收到此消息...

错误信息

我希望将其更改为“缺货,请联系我们的销售办事处”

有谁知道我可以放入什么代码来functions.php实现这一点?

我尝试了这个代码片段,奇怪的是,如果我在我的购物篮中添加 9 个项目,然后尝试添加另一个 1,我可以得到正确的消息出现......

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 are currently trying to order more of this product than are currently available at your shipping location. Please call our sales team to discuss availability", $domain );
}

return $translated;
}

对此事的任何帮助将不胜感激

标签: phpwordpresswoocommerceproductcart

解决方案


注:两者有区别

  • 您无法将该数量的 ... 添加到购物车,因为没有足够的库存(...剩余)
  • 您不能将该金额添加到购物车中 - 我们有 ... 有库存,而您已经有 ... 在您的购物车中

即使它们相似,它们也会彼此分开显示


自 WooCommerce 4.5.0以来编辑“库存不足”消息的方式是使用woocommerce_cart_product_not_enough_stock_message过滤器挂钩。

/**
 * Filters message about product not having enough stock.
 *
 * @since 4.5.0
 * @param string     $message Message.
 * @param WC_Product $product_data Product data.
 * @param int        $stock_quantity Quantity remaining.
 */
function filter_woocommerce_cart_product_not_enough_stock_message( $message, $product_data, $stock_quantity ) {
    // New message
    $message = __( 'You are currently trying to order more of this product than are currently available at your shipping location. Please call our sales team to discuss availability', 'woocommerce' );
    
    return $message;
}
add_filter( 'woocommerce_cart_product_not_enough_stock_message', 'filter_woocommerce_cart_product_not_enough_stock_message', 10, 3 );


自 WooCommerce 5.3.0以来编辑“购物车中的库存不足”消息的方式是使用woocommerce_cart_product_not_enough_stock_already_in_cart_message过滤器挂钩。

/**
 * Filters message about product not having enough stock accounting for what's already in the cart.
 *
 * @param string $message Message.
 * @param WC_Product $product_data Product data.
 * @param int $stock_quantity Quantity remaining.
 * @param int $stock_quantity_in_cart
 *
 * @since 5.3.0
 */
function filter_woocommerce_cart_product_not_enough_stock_already_in_cart_message( $message, $product_data, $stock_quantity, $stock_quantity_in_cart ) {
    // New message
    $message = __( 'You are currently trying to order more of this product than are currently available at your shipping location. Please call our sales team to discuss availability', 'woocommerce' );
    
    return $message;
}
add_filter( 'woocommerce_cart_product_not_enough_stock_already_in_cart_message', 'filter_woocommerce_cart_product_not_enough_stock_already_in_cart_message', 10, 4 );

推荐阅读