I’m trying to limit the number of characters our WooCommerce product titles have, I found this PHP code:
add_filter( 'the_title', 'shorten_woo_product_title', 10, 2 );
function shorten_woo_product_title( $title, $id ) {
if ( ! is_singular( array( 'product' ) ) && get_post_type( $id ) === 'product' ) {
return substr( $title, 0, 30); // change last number to the number of characters you want
} else {
return $title;
}
}
It works but I would like it to show the "…" at the end of each product title.
4
Answers
You can use
strlen()
php function to target specific product title length to append…
to shortened title when product title is over a specific length:Code goes in functions.php file of the active child theme (or active theme). Tested and works.
I use this code and change the character numbers to 40 but then it goes to 2nd line and then the alignment of add to cart button disturb, it get changed from other products alignmen .
add_filter( ‘the_title’, ‘shorten_woo_product_title’, 10, 2 ); function shorten_woo_product_title( $title, $id ) { if ( ! is_singular( array( ‘product’ ) ) && get_post_type( $id ) === ‘product’ && strlen( $title ) > 30 ) { return substr( $title, 0, 30) . ‘…’; // change last number to the number of characters you want } else { return $title; } }
You could do this with CSS by adding the following style attributes to the element containing the content you want to ellipsize. This would ensure that the content always displays to the edge of the element, without over-flowing.
This method should be more performant than the JS solution and when implementing functionality like this, I’d always choose a pure-CSS solution if possible, before reverting to Javascript or trimming the string on the backend.