phphtmlwordpresswoocommerceproduct

Add a line break to Woocommerce cart item names and order item names


Context
This question is a follow-up on the previous question titled Add a line break in Woocommerce Product Titles

To me the code in this topic (seen here below) works like a charm, when adding it to my child astra theme. I have a question to upgrade this code a bit, hoping some smart developers out there might help me.

//ADD LINE BREAK
add_filter( 'the_title', 'custom_the_title', 10, 2 );
function custom_the_title( $title, $post_id ) {
    $post_type = get_post_field( 'post_type', $post_id, true );
    if( $post_type == 'product' || $post_type == 'product_variation' )
        $title = str_replace( '|', '<br/>', $title ); // we replace '|' by '<br>'
    return $title;
}

So i change the products names under woocommerce products to "name | here" getting the result like this in the frontend product gallery

"Name
Here"

The Question
Code works like a charm in the product gallery, all it good - but this is were my problem comes in. It shows a ' | ' on all subpages such as 'basket' and 'menu cart' aswell. I have two option i'd like to try out:

  1. how to integrate the code to hit all of the other pages (like the menu cart and basket, and maybe more) and not only the product gallery?

or

  1. How to make the '|' and thereby the "<br/>" only be permitted on the product gallery page, resulting in hiding and/or working as a 'diplay: none' on all other pages?

Hope you can help me people.


Solution

  • To alter the product name display on cart items, minicart and order items (+ email notifications), use the following additional code:

    // For mini cart and cart item name
    add_action( 'woocommerce_cart_item_name', 'alter_wc_cart_item_name', 10, 2 );
    function alter_wc_cart_item_name( $item_name, $cart_item ) {
        if ( strpos($item_name , '|') !== false ) {
            $item_name = str_replace( '|', '<br/>', $item_name );
        }
        return $item_name;
    }
    
    // For order item name (even on email notifications)
    add_action( 'woocommerce_order_item_name', 'alter_wc_order_item_name', 10, 2 );
    function alter_wc_order_item_name( $item_name, $item ) {
        if ( strpos($item_name , '|') !== false ) {
            $item_name = str_replace( '|', '<br/>', $item_name );
        }
        return $item_name;
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.