Your question should be specific to WordPress. Generic PHP/JS/SQL/HTML/CSS questions might be better asked at Stack Overflow or another appropriate Stack Exchange network site. Third-party plugins and themes are off-topic for this site; they are better asked about at their developers' support routes.
Closed 4 years ago.
Improve this questionHi guys I've searched this for too long and I am getting tired now. I need to set a limit on my post titles but I don't know how to do it. On google there are snippets of 300000000 codes to do the same thing but I don't understand where to put these and HOW. I am a total newbie. I am building my website with Elementor and I need the title to trim at an exact character limit. How do I do it? Please help me!!
Closed. This question is off-topic. It is not currently accepting answers.Your question should be specific to WordPress. Generic PHP/JS/SQL/HTML/CSS questions might be better asked at Stack Overflow or another appropriate Stack Exchange network site. Third-party plugins and themes are off-topic for this site; they are better asked about at their developers' support routes.
Closed 4 years ago.
Improve this questionHi guys I've searched this for too long and I am getting tired now. I need to set a limit on my post titles but I don't know how to do it. On google there are snippets of 300000000 codes to do the same thing but I don't understand where to put these and HOW. I am a total newbie. I am building my website with Elementor and I need the title to trim at an exact character limit. How do I do it? Please help me!!
Share Improve this question asked Nov 17, 2020 at 18:17 LorenzoLorenzo 112 bronze badges 1- 3rd party plugin dev support is off topic here, if a standard WP answer does not work for you, or this isn't a standard post title, then you'll need to ask Elementor support or go to an Elementor community to ask. If you already have a snippet though you should share that and ask where it goes – Tom J Nowell ♦ Commented Nov 17, 2020 at 19:06
1 Answer
Reset to default 1Exactly "where" may differ depending on your theme setup. However, there are some global-ish ways to do this if you want to tackle it that way.
add_filter( 'the_title', 'my_trim_words' );
function my_trim_words( $title )
{
// limit to ten words
return wp_trim_words( $title, 10, '' );
}
If you'd like to do this for a particular post type, you can do it like this:
add_filter( 'the_title', 'my_trim_words_by_post_type', 10, 2 );
function my_trim_words_by_post_type( $title, $post_id )
{
$post_type = get_post_type( $post_id );
if( 'product' == $post_type ) {
return $title;
// limit to ten words
return wp_trim_words( $title, 10, '' );
}
If it's within the theme templates (frontend files) that you're wanting to do this in very specific areas, you can use it this way in your templates:
<?php echo wp_trim_words( get_the_title(), 5 ); ?>