在 WooCommerce 4.5+ 中隐藏或编辑 "You cannot add another 'xxx' to your cart" 错误消息

Hide or edit the "You cannot add another 'xxx' to your cart" error message in WooCommerce 4.5+

通过产品设置我启用了“单独销售:启用此功能只允许在一个订单中购买一件商品”

将相同的产品添加到购物车时出现错误消息,因为我启用了此设置。错误消息是 “您不能将另一个 'xxx' 添加到您的购物车”。我不想将相同的产品添加到购物车,所以这很好用并且 不错

我的问题:

如何隐藏错误消息 “您无法将另一个 'xxx' 添加到您的购物车”

如果我使用 CSS 代码

.woocommerce-error {
    display: none;
}

然后我们登录时的错误密码或邮箱也被隐藏了,我不想隐藏另一个错误信息。

只隐藏这个错误是否可以实现?

要编辑消息,您可以使用自 WooCommerce 4.5.0 以来的 woocommerce_cart_product_cannot_add_another_message 过滤器挂钩。

/**
 * Filters message about more than 1 product being added to cart.
 *
 * @since 4.5.0
 * @param string     $message Message.
 * @param WC_Product $product_data Product data.
 */
function filter_woocommerce_cart_product_cannot_add_another_message( $message, $product_data ) {
    // New text
    $message = __( 'My new message', 'woocommerce' );

    return $message;
}
add_filter( 'woocommerce_cart_product_cannot_add_another_message', 'filter_woocommerce_cart_product_cannot_add_another_message', 10, 2 );

要完全隐藏消息,只需替换

// New text
$message = __( 'My new message', 'woocommerce' );

// New text
$message = '';

但是,上述解决方案的“问题”是消息现在被隐藏了,但是 woocommerce-error(红框)和 view-cart 按钮仍然显示。


因此,在使用过滤器挂钩时,您可以添加一些额外的 jQuery 来隐藏 woocommerce-error

注意:虽然下面的方法有效,但隐藏错误信息绝不是一个好主意。这些都是有原因的,让客户知道一些事情。因此,这个解决方案有点'tricky'.

但是要回答你的问题,你可以使用:

function filter_woocommerce_cart_product_cannot_add_another_message( $message, $product_data ) {    
    $message = '<div class="hide-this-error-message"></div>';
    
    return $message;
}
add_filter( 'woocommerce_cart_product_cannot_add_another_message', 'filter_woocommerce_cart_product_cannot_add_another_message', 10, 2 );

function action_wp_footer() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            $( '.hide-this-error-message' ).closest( 'ul.woocommerce-error' ).hide();
        });
    </script>
    <?php
}
add_action( 'wp_footer', 'action_wp_footer' );