Wordpress How-To : Week 1 – The Excerpt

Posted on Oct 12, 2008 in Wordpress
Wordpress How-To : Week 1 – The Excerpt

I’ve decided to make some changes to the blog. One is to write a weekly series of “Wordpress How-To’s” . Every monday I’ll try to find something interesting about Wordpress and write about it . Ok…now let’s begin.

Week 1 : Wordpress Excerpt – how to limit the number of words displayed

The excerpt displays the first 55 words of a post…a “teaser” if you like.It’s usually used on front pages of blogs and online newspapers . Unlike the_content() , the_excerpt() does not show a “Read More” link after the text …this is replaced by [..] .

Today we’ll learn how to change the number of words displayed by the excerpt.Let’s say that you don’t have the space to show the first 55 words of a post/article and you would like to show only the first 25.This is how you do it :

First of all you’ll need to open the functions.php file of your theme and add these following lines:

<?php
function string_limit_words($string, $word_limit)
{
  $words = explode(' ', $string, ($word_limit + 1));
  if(count($words) > $word_limit)
  array_pop($words);
  return implode(' ', $words);
}
?>

Then add this where you want the excerpt to be displayed :

<?php $excerpt = get_the_excerpt();
 echo string_limit_words($excerpt,25);
?>

Enjoyed this post ? Subscribe and Share

  • RSS Feed
  • Get Email Updates
  • Digg
  • Del.icio.us
  • StumbleUpon
  • DesignFloat
  • Reddit

4 Comments

  1. jSteven says:

    Cool.I’ve been using the_content_rss until now and it’s been a pain in the ass.

  2. Eugene says:

    looking forward for more information about this. thanks for sharing. Eugene

  3. JRS says:

    You’ll probably want to delete my first two comments… when I try to paste in the typo-corrected code only part of it makes it through the submission process for some reason. I know when you look at your text on the page at first glance it appears there is no typo in the line:
    return implode(‘ ‘,$words);

    but if you magnify the page you’ll see that the second ‘ is actually reversed. Weird.

  4. Iacob Ionut says:

    I’ll probably have to put the code in a file and make it available to download to get rid of all the copy – paste errors.
    Thanks for noticing.

Leave a Comment