Sometimes when creating WordPress themes you might want to automatically limit the length of post text that is displayed in the main page post teaser view to make things easier for clients when writing articles. You could use a plugin like limit-post etc but I always find it much easier to contain all these type of modifications within the themes own functions.php file. This little WordPress hack will allow you to limit the displayed post text by a defined number of words on your blogs home page.
The code snippet below should be placed somewhere within your WordPress themes functions.php. If your WordPress theme does not have a functions.php file simply create one with your favorite text editor and place it in your WordPress themes folder.
function string_limit_words( $string, $word_limit ) {
$words = explode( ' ', $string, ( $word_limit + 1 ) );
if( count( $words ) > $word_limit )
array_pop( $words );
return implode( ' ', $words );
}
Now to automatically limit the number of words displayed in your post text you simply add and edit the code below to you WordPress theme. Usually this will replace the_content() code within your themes index.php and any other sections on your blog where you would like to limit the teaser text output like archives, search etc.
$excerpt = get_the_excerpt(); echo string_limit_words( $excerpt, 40 );
To control the number of words displayed on your blogs home page from the main article post you can simply edit the 40 within the second piece of code. 40 means this will only show 40 words so if you set it to 50 it will show 50 words.
Within your single.php you should leave the_content()
code in place otherwise the full article text will not show within post pages.
Leave a Reply