Home > OS >  Change seperator %s variable message: 'you cannot add another "%s" to your cart'
Change seperator %s variable message: 'you cannot add another "%s" to your cart'

Time:05-17

I want to make changes to this message : You cannot add another "%s" to your cart.

If the product has a variable, output %s is as follows : product-name | variable1, variable2

I want the output to be this way : product-name | variable1 , variable2

I want to change ',' to ' , '

I found the text hook but I do not know if it should be used to change change ',' to ' , '. Any advice?

Path : 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" >%s</a> %s', wc_get_cart_url(), __( 'View cart', 'woocommerce' ), $message ) );
    }
}

CodePudding user response:

As you can see your code contains the woocommerce_cart_product_cannot_add_another_message filter hook, which allows you to edit the $message. Then you can use str_replace()

So you get:

/**
 * 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 );
  • Related