Custom Excerpt Lengths in WordPress

Posted on: January 17th, 2013

Note: This will throw an error if you are using PHP 5.2 or lower. 5.3 and above will be fine. Thanks to FoxyPaco for the info.

WordPress generally handles all of your content pretty nicely, including the excerpt, but sometimes you need a custom excerpt length and WordPress doesn’t support that out of the box. After some looking around on the internet I came across two solutions. First, an out-of-date plugin that wasn’t going to get the job done and a custom piece of code that goes into functions.php.

I went with the latter and chucked this block of code into my functions.php file.

function custom_excerpt($new_length = 20, $new_more = '...') {

  // use the variable passed from $new_length as the length of the excerpt
  add_filter('excerpt_length', function () use ($new_length) {
    return $new_length;
  }, 999);

  // determine what comes at the end of the excerpt (in this case ...)
  add_filter('excerpt_more', function () use ($new_more) {
    return $new_more;
  });

  // generate the current excerpt
  $output = get_the_excerpt();

  // use wptexturize to basically sanitize the excerpt
  $output = apply_filters('wptexturize', $output);

  // convert_chars to remove metadata tags and convert others to unicode 
  $output = apply_filters('convert_chars', $output);

  // wrap it back up in p tags
  $output = '<p>' . $output . '</p>';
  // the above line may not be needed depending on the status of wpautop

  // echo that sucker
  echo $output;
}

So that looks long, but if you take the comments out, it’s much shorter. It gives you complete control over your excerpts and all you have to do is switch from using

<?php the_excerpt(); ?>

to

<?php custom_excerpt(); ?>

After you use the new function you can place any number inside the () and that number will then be passed as the new $new_length variable discussed in the code above.

Note: if you try to use the_excerpt(); later in the template, it will default to the closest custom_excerpt() number. Thanks @pbaylies for pointing this out.

That’s all you have to do for a shiny custom excerpt length, thanks to LordAzriel on the support forums. The thing I like the most about this custom excerpt length is that you can use it wherever you want and just place a new number inside the function. No more going back to functions.php every time you want a new length. It’s easy, simple and the options for custom excerpt lengths become as endless as you could want. It’s all just a new number inside ().

If you have a better way to accomplish this, let me know. I’d be happy to hear about it.

convert_chars in the Codex
wptexturize in the Codex

Note: The forum topic says it will only work if you are running PHP 5.3 or higher, which you hopefully are.

Tags: ,

previous post: Fixing upload_max_filesize In php.ini next post: Installing Sass and Compass