Customize The Excerpt Length in WordPress Using PHP

Customize The Excerpt Length in WordPress Using PHP

Use this simple PHP function to custom content excerpts.

·

2 min read

If you dabble in WordPress development even the slightest bit, you know about the famous the_excerpt(); function in WordPress core. If you aren't familiar, the function returns a shortened string of the content for the current post or page. The string is relieved of all HTML tags or styling. Great for creating post feeds in your theme!

This function is handy, but it is limiting. By default, the length of the excerpt is 55 words. The length can be changed to any size you desire by placing the following function in your theme's functions.php file:

/**
 * Filter the except length to 20 words.
 *
 * @param int $length Excerpt length.
 * @return int (Maybe) modified excerpt length.
 */
function wpdocs_custom_excerpt_length( $length ) {
   return 20;
}
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );

Simple right? This is nice for getting it where you want it, but you're still limited to whatever the new limit is. What if you need it to be 20 words on your blog's feed, and 75 words on your events feed?

Well, here is a simple function that will do just that!

/**
 * Filter the except length to any specified length of words.
 *
 * @param string $content the content
 * @param int $length Excerpt length.
 * @return int (Maybe) modified excerpt length.
 */
function catchy_labs_custom_excerpt($content, $limit) {
  $excerpt = explode(' ', strip_tags($content), $limit);

  if (count($excerpt)>=$limit) {
      array_pop($excerpt);
      $excerpt = implode(" ",$excerpt).' [...]';
  } else {
      $excerpt = implode(" ",$excerpt);
  }

  $excerpt = preg_replace('`[[^]]*]`','',$excerpt);
  return $excerpt;
}

The idea is simple. Inside of your post loop, instead of calling the_excerpt();, you can make this call instead:

$length = 45;
$content = get_the_content();

echo catchy_labs_custom_excerpt( $content, $length );

get_the_content(); grabs the post's content (tags and all) in a PHP variable we can pass to our custom function. Just output the returned string and you're done!

Did you find this article valuable?

Support Bobby by becoming a sponsor. Any amount is appreciated!