How to limit the excerpt to a number of characters, instead of words

I sometimes find inconvenient the way WordPress trims the excerpt by default, which is by number of words. The number of characters in a word varies so greatly, that trimming by number of words makes the excerpt's length horribly inconsistent.

I sometimes find inconvenient the way WordPress trims the excerpt by default, which is by number of words.

The number of characters in a word varies so greatly, that trimming by number of words makes the excerpt’s length horribly inconsistent.

The main reasons I usually choose trimming the excerpt by number of characters are:

  • I want a neat content grid with consistent thumbnails and excerpts sizes.
  • I’m working with German language. This – of course – would apply to any other language in which words vary from 1 character to the sky is the limit, rendering all over the place excerpt lengths.

Whatever your reason for preferring the character number limit over WordPress’ default, the solution is simple.

Just add the following snippet in your theme’s functions.php file:
(NOTE: if you are using a child theme, add the code to the child theme’s functions.php file)

/**
 * Limit excerpt to a number of characters
 * 
 * @param string $excerpt
 * @return string
 */
function custom_short_excerpt($excerpt){
	return substr($excerpt, 0, 200);
}
add_filter('the_excerpt', 'custom_short_excerpt');

[panel type=”info”]Replace 200 with your desired number of characters.[/panel]

Note that this will trim the excerpt to a precise number of characters, cutting into the last word where necessary.

Some will not be ok with that. But remember that the last word could have 50 characters for example, so not cutting it will give the same inconsistency in excerpt lengths, therefore defying the purpose of the character limit solution.

Nevertheless, if you prefer not cutting, use this snippet instead:

/**
 * Limit excerpt to a number of characters without cutting last word
 * 
 * @param string $excerpt
 * @return string
 */
function custom_short_excerpt($excerpt){
	$limit = 200;

	if (strlen($excerpt) > $limit) {
		return substr($excerpt, 0, strpos($excerpt, ' ', $limit));
	}

	return $excerpt;
}

add_filter('the_excerpt', 'custom_short_excerpt');

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *