Shortening the_excerpt in wordpress with substr



Things have been very busy here for the last couple of months, so sorry for the lack of posts. We hope to resume normal posting shortly.

In the meantime, here’s a quick and simple wordpress tip that’s come in handy for us so we thought it would be good to share.

One common problem you can run into, when customising wordpress themes, is the default length of  text returned by the handy template tag the_excerpt . The default, which is set at 55 words (not characters!) is often to big a chunk to fit its required purpose – that of providing a teaser for posts.

What to do? Well, you can add code into the functions.php file to change the default size of the_excerpt site-wide – as detailed here

What, though, if you just want to reduce the excerpt on a specific page – for example on your home page (by default index.php)?

Using the simple php command  substr you can reduce the_excerpt directly in the loop.  You’re going to have to use the get_the_excerpt hook first though, as you can’t run substr directly on the_excerpt template tag.

Let’s take the example of the front page:

The loop starts here: <?php while (have_posts()) : the_post(); ?> returning template tags like the_title(), the_author(), and the_excerpt() for use within the template.

We’re going to create a variable called $excerpt and assign the contents of get_the_excerpt() to it. So <?php while (have_posts()):the_post();$excerpt=get_the_excerpt();?>

Then, wherever in your template you want to reduce the size of the_excerpt simply replace it with <?php echo substr($excerpt,0,x);?> where x is the number of characters (not words!) that you want to display.  So, to display an excerpt of 50 characters you would have <?php echo substr($excerpt,0,50);?>

Adding a ‘Read More’ link

You should, of course, provide a link to the full post when using the_excerpt or any variation on it. To do that, simply add <a href=”<?php echo the_permalink();?>”>[ read more…]</a> immediately after your excerpt code.


Tags: , , ,