'Trim product name on WooCommerce product loop
I would like to trim the product title on the shop page or anywhere that there are more than one products (like homepage product sliders etc). For now, i have this code
<?php
function shorten_woo_product_title($title, $id) {
if (!is_product()) {
$title = wp_trim_words($title, 7);
return $title;
}
else {
return $title;
}
add_filter('the_title', 'shorten_woo_product_title', 10, 2); ?>
This works just fine but it trims the posts that i display in my homepage and it makes my site doesn't load the blog page. I only want to trim product titles and not post titles too. I also want to trim product titles at the related products section inside single product page. FYI: this code was added in functions.php file.
Solution 1:[1]
function shorten_woo_product_title($title, $id) {
if (is_shop() || is_product_category() || is_product_tag() || is_home() || is_front_page()) {
if (get_post_type($id) == 'product') {
$title = wp_trim_words($title, 7);
}
}
return $title;
}
add_filter('the_title', 'shorten_woo_product_title', 10, 2);
Solution 2:[2]
I use this code and change the character numbers to 40 but then it goes to the 2nd line and then the alignment of add to cart button disturb, it gets changed from other products alignment.
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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Suraj Rao |
