WordPress shows 55 words in its default excerpt. What if you need to limit the character length of the excerpt in WordPress instead?

When do you need to fix the character length of the excerpt?

You know that some words can be very long and some short. Because of this, default excerpt of the WordPress varies in character length. There are some cases when you need to have excerpt of fixed lines. For example, you want to show posts in gridview and want all the post grid with same height. (You can take the homepage of our website as an example.) In this case, you have two options, either fix the height of grid by CSS and hide the overflowed text (as done in our website) or pull excerpt with fixed character length only.

Here, we are going to learn how to get excerpt of fixed length of character.

How to display excerpt with fixed character length?

You can do this with the help of a simple function. You need to put this function in the functions.php of or your theme and then call it whenever you need excerpt with fixed character length.

Here’s the code of the function:


// For excerpt with charlength as asked
function the_excerpt_max_charlength($charlength) {
$excerpt = get_the_excerpt();
$charlength++;

if ( mb_strlen( $excerpt ) > $charlength ) {
$subex = mb_substr( $excerpt, 0, $charlength - 5 );
$exwords = explode( ' ', $subex );
$excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
if ( $excut < 0 ) {
echo mb_substr( $subex, 0, $excut );
} else {
echo $subex;
}
echo '[...]';
} else {
echo $excerpt;
}
}

Now, wherever you need to echo excerpt, you need to call this function:


<?php the_excerpt_max_charlength(140); ?>

In above function call, you’re sending 140 as parameter. This parameter is actually the character length that you want to be shown. Sending 140 as parameter echos excerpt with 140 characters.

Wrapping Up

Limiting the character length of excerpt helps in different contexts. This easy to implement function is what I am using in my projects. You can try it in your site. If you have any question about it, you can put them below in the comment box. I’d love to help you as far as possible.

Lots more important posts are awaiting you. So, keep following WPCounsel.