Is there a way to limit the word count of the post title?
I searched over the internet but found nothing.
All I know is, only the content of the post can be limited or excerpted.
simply use this where ever you want to display your title with limited words
<?php echo wp_trim_words( get_the_title(), 5 ); ?>
replace number 5 in above code with whatever number of words you need to display.
Regards.
If continue sign "..." needed at end of title
<?php
echo wp_trim_words( get_the_title(), 10, '...' );
?>
If continue sign "..." not needed at end of title
<?php
echo wp_trim_words( get_the_title(), 10 );
?>
There is a built-in function for that: wp_trim_words()
.
add_filter( 'the_title', 'wpse_75691_trim_words' );
function wpse_75691_trim_words( $title )
{
// limit to ten words
return wp_trim_words( $title, 10, '' );
}
If you want to trim the words depending on certain properties of the post, ask WP to pass the post ID to your callback. Here is an example for filtering by post type. But you can also check for associated terms, post age or author, and even post meta.
add_filter( 'the_title', 'wpse_75691_trim_words_by_post_type', 10, 2 );
function wpse_75691_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, '' );
}
add_filter( 'the_title', 'wpse_75691_trim_words' ); function wpse_75691_trim_words( $title ) { $cur_pt = get_post_type(); if( 'some_post_type' == $cur_pt ) { // limit to ten words return wp_trim_words( $title, 10, '' ); } else { return $title; } }
function limit_word_count($title) {
$len = 5; //change this to the number of words
if (str_word_count($title) > $len) {
$keys = array_keys(str_word_count($title, 2));
$title = substr($title, 0, $keys[$len]);
}
return $title;
}
add_filter('the_title', 'limit_word_count');
You can put any kind of limit on almost anything you like, you just need the correct filter