在 WooCommerce 中更改分隔符 %s 变量消息:'you cannot add another "%s" to your cart'

Change seperator %s variable message: 'you cannot add another "%s" to your cart' in WooCommerce

我想更改此消息:您不能将另一个“%s”添加到您的购物车。

如果产品有变量,输出%s如下:产品名称| 变量 1,变量 2

我希望输出是这样的:产品名称 | 变量 1 , 变量 2

我想把','改成' , '

我找到了文本挂钩,但我不知道是否应该使用它来将 ',' 更改为 ' , '。有什么建议吗?

路径:plugins/woocommerce/includes/class-wc-cart.php

// Force quantity to 1 if sold individually and check for existing item in cart.
if ( $product_data->is_sold_individually() ) {
    $quantity      = apply_filters( 'woocommerce_add_to_cart_sold_individually_quantity', 1, $quantity, $product_id, $variation_id, $cart_item_data );
    $found_in_cart = apply_filters( 'woocommerce_add_to_cart_sold_individually_found_in_cart', $cart_item_key && $this->cart_contents[ $cart_item_key ]['quantity'] > 0, $product_id, $variation_id, $cart_item_data, $cart_id );

    if ( $found_in_cart ) {
        /* translators: %s: product name */
        $message = sprintf( __( 'You cannot add another "%s" to your cart.', 'woocommerce' ), $product_data->get_name() );

        /**
         * 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.
         */
        $message = apply_filters( 'woocommerce_cart_product_cannot_add_another_message', $message, $product_data );

        throw new Exception( sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', wc_get_cart_url(), __( 'View cart', 'woocommerce' ), $message ) );
    }
}

如您所见,您的代码包含 woocommerce_cart_product_cannot_add_another_message 过滤器挂钩,它允许您编辑 $message。然后你可以使用 str_replace()

所以你得到:

/**
 * 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 ) {
    // Replace all occurrences of the search string with the replacement string
    $product_data_name = str_replace( ',', ' , ', $product_data->get_name() );

    // New text
    $message = sprintf( __( 'You cannot add another "%s" to your cart.', 'woocommerce' ), $product_data_name );

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