Yan asked: “How to limit the size of the post excerpt without using a plugin?”

Yan, who’s a regular reader of my blogs, asked me how he can limit the length of the post excerpt without using a plugin. Come on, my friend, I got what you need!

Nothing hard here. Edit your single.php file and replace the the_excerpt() function by the following code:

<?php
$len = 50; //Number of words to display in excerpt
$newExcerpt = substr($post->post_excerpt, 0, $len); //truncate excerpt according to $len
if(strlen($newExcerpt) < strlen($post->post_excerpt)) {
    $newExcerpt = $newExcerpt."[...]";
}
echo "<p>".$newExcerpt."</p>"; //finally display excerpt
?>

Let's have a look at the code: First, we define the desired number of words for the post excerpt. It is defined to 50 in this example. Then, we use the php substr() function to get only the 50 first words of the excerpt.
We verify that our new excerpt isn't shorter than the excerpt recorded in the database. If it is, we add [...].
And finally, we display our 50 words long excerpt.

Leave a Comment

* Name, Email, Comment are Required