Add a line break in Woocommerce Product Titles
Let's say my product title is:
Brown Colored Leather Shoes
But based on my column width the title looks like this:
Brown Colored Leather
Shoes
I know it's possible to do a character replacement so that a "|"
in the backend becomes a line break <br/>
. But I don't know how.
I want it to look like this
Brown Colored
Leather Shoes
I found these references:
Adding a break to product title on shop pages for a certain length
https://medium.com/@clarklab/add-a-line-break-in-a-wordpress-title-b3aeff346037
Is it possible to add a line break to WC products long titles?
2020 revision - Still works on Wordpress 5.5.1 with WooCommerce 4.4.1
Using this custom function hooked in the_title
filter hook will do the job (replacing a pipe character |
by a <br>
in product titles):
add_filter( 'the_title', 'custom_product_title', 10, 2 );
function custom_product_title( $title, $post_id ){
$post_type = get_post_field( 'post_type', $post_id, true );
if( in_array( $post_type, array( 'product', 'product_variation') ) ) {
$title = str_replace( '|', '<br/>', $title ); // we replace "|" by "<br>"
}
return $title;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Code is tested on Woocommerce 3+ and works.
Now you can target different product pages with the WC conditionals tags as
is_product()
,is_shop()
,is_product_category()
oris_product_tag()
(and many others)…
The full answer working as Nov 2019 with Wordpress 5.2.4:
//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;
}
Credits to LoicTheAztec and Coes