Categories
Tutorials

Limiting WordPress Excerpt Length (How To)

WordPress will present your excerpt in a really ugly way. It’ll remove paragraphs and put it all into a blob.

Table of Contents

But you can fix it using the function below. Put it in your functions.php. I just put it at the end of the document.

function end_with_sentence( $excerpt ) {

    // Limit excerpt to 140 char

    $excerpt = substr( $excerpt, 0, 140 );

    if ( ( $pos = mb_strrpos( $excerpt, '.' ) ) !== false ) {

      $excerpt = substr( $excerpt, 0, $pos + 1 );

    }

    return $excerpt;

  }

Here’s how it works.

The end_with_sentence function takes a string $excerpt and returns a version of it that’s truncated to the last full sentence within the first 140 characters.

If there’s no period within the first 140 characters, it simply returns the first 140 characters.

    $excerpt = substr( $excerpt, 0, 140 );

This line uses the substr function to limit the length of $excerpt to the first 140 characters.

After this line, $excerpt will contain at most the first 140 characters of its original value.

If you want it shorter or longer, change the value that’s currently 140. You can change it to 280 or whatever you want.

    if ( ( $pos = mb_strrpos( $excerpt, '.' ) ) !== false ) {

This line checks if there’s a period (.) within the first 140 characters of $excerpt.

The mb_strrpos function finds the last occurrence of a substring (in this case, a period) in a string.

If a period is found, its position is stored in $pos. If no period is found, mb_strrpos returns false.

      $excerpt = substr( $excerpt, 0, $pos + 1 );

If a period was found in the previous line, this line truncates $excerpt to end right after the last period within the first 140 characters. The + 1 ensures that the period itself is included in the final $excerpt.

The theme I’m using is the Twenty Twenty theme from WordPress, I am unsure why there isn’t a “Read More” hyperlink, so I had to add one.

I added this into the content.php template part file, found in the template-parts folder of the theme.

However, your theme might have the relevant section somewhere else. The key to finding the correct file is looking for the function the_excerpt();

Then, place this code below where you found the_excerpt() :

echo sprintf( '<br><a class="read-more" href="%1$s">%2$s</a>',get_permalink( get_the_ID() ), __( 'Read More', 'twentytwenty' ));

You can find the correct file by doing a search. In Visual Studio Code, just press CTRL + SHIFT + F, or click on the magnifying glass on the left sidebar. Then, search the_excerpt

It might take a bit of digging because you might have other themes or files with the same function.

Results of shortening excerpt

Here it is.

From…

wordpress excerpt shortening

To…

wordpress excerpt shortened

Have a project in mind?

Websites. Graphics. SEO-oriented content.

I can get your next project off the ground.

See how I have helped my clients.