Search code examples
phpwordpresswoocommercecartcharacter-trimming

Hiding middle-dash in mini-cart (theme functions.php)


I am currently preparing an online store based on Woocommerce, but I have a problem with the appearance of a mini-cart. Whenever the name of a particular product is too long, it causes the problems with the mini-cart ( which do not fit to .cart_wrapper).

I decided to hide the least important elements of (repeated) the product names. I used the following code :

function wpse_remove_shorts_from_cart_title( $product_name ) {
    $product_name = str_ireplace( 'premium', '', $product_name );
    $product_name = str_ireplace( 'standard', '', $product_name );

    return $product_name;
}
add_filter( 'woocommerce_cart_item_name', 'wpse_remove_shorts_from_cart_title' );

And it works great. With an example of the product name:

Car Carpet VW (1999-2001) - PREMIUM

I got:

Car Carpet VW (1999-2001) -

Now the problem for me is the middle-dash occurring at the end of the product name.

I can't remove it using the methods described above, because by doing it this way, it removed also the middle-dash inside the brackets (the one which separates the years or production).

Since my knowledge of PHP is very basic - I turn to you with the question - whether there are any tags which would allow me to hide the middle-dash at the end of the name, while leaving the existing middle-dash between the brackets.

How can I do that?


Solution

  • Yes it's possible with the native php function rtrim(). you will use it this way:

    <?php
        $string1 = 'Car Carpet VW (1999-2001) - PREMIUM';
        $string2 = 'Car Carpet VW (1999-2001) -';
        $string1 = rtrim($string1, ' -');
        $string2 = rtrim($string2, ' -');
        echo '$string1: '.$string1.'<br>'; // displays "Car Carpet VW (1999-2001) - PREMIUM"
        echo '$string2: '.$string2.'<br>'; // displays "Car Carpet VW (1999-2001)"
    ?>
    

    References: PHP function rtrim()