How to trim the_excerpt to a certain character count

How to limit the_excerpt to a number of characters

WordPress builds post excerpts with the_excerpt(). By default it outputs the first 55 words of the post. But what if the limit should be in characters, not words? For example, we need the first 120 characters of the post. You can find many solutions on the Internet, but most of them require changes inside the loop or in the theme templates, which is not always practical and makes the code harder to maintain. The solution below is a short filter for your functions.php file.

In addition, here are a few more filters that change the default behaviour of the_excerpt() and that I use on almost every project: changing the number of words, replacing the […] at the end, and adding a link to the post.

Limit the excerpt to 120 characters

add_filter( 'get_the_excerpt', 'helloadmin_excerpt_chars', 20 );
function helloadmin_excerpt_chars( $excerpt ) {
    $limit   = 120;
    $excerpt = wp_strip_all_tags( $excerpt );

    if ( mb_strlen( $excerpt ) <= $limit ) {
        return $excerpt;
    }

    // Cut at the limit, then back to the last full word.
    $excerpt = mb_substr( $excerpt, 0, $limit );
    $excerpt = preg_replace( '/\s+\S*$/u', '', $excerpt );

    return $excerpt . '…';
}

The filter runs on get_the_excerpt, so it works on plain text before the_excerpt() wraps it in a paragraph. If you trim the output of the the_excerpt filter instead, the HTML tags count as characters and can be cut in half. mb_substr() is used instead of substr() so multibyte characters are not broken.

Change the excerpt length in words

add_filter( 'excerpt_length', 'helloadmin_excerpt_length' );
function helloadmin_excerpt_length( $length ) {
    return 20; // Excerpt length is 20 words.
}

Replace […] at the end of the excerpt

add_filter( 'excerpt_more', 'helloadmin_excerpt_more' );
function helloadmin_excerpt_more( $more ) {
    return '…';
}

Add a “Read more” link at the end of the excerpt

Use this instead of the previous filter, not together with it: both change the same excerpt_more value, and the one that runs last wins.

add_filter( 'excerpt_more', 'helloadmin_excerpt_read_more' );
function helloadmin_excerpt_read_more( $more ) {
    return ' <a href="' . esc_url( get_permalink() ) . '">' . esc_html__( 'Read more…', 'helloadmin' ) . '</a>';
}

Note that excerpt_more is applied only to automatically generated excerpts. If a post has a manual excerpt in the Excerpt field, the link is not added.

Sources:

  1. https://wpquestions.com/How_do_I_trim_the_excerpt_to_a_certain_character_count/716
  2. https://developer.wordpress.org/reference/hooks/get_the_excerpt/