The WordPress excerpt via the_excerpt() function is a brief summary of a post from your WordPress blog that appears where it is called, usually on archive pages (categories, tag, author pages), results search and, in some cases, on the home page of your site, but also in the RSS feed and in what is sometimes sent to social networks via specific extensions.
By default, WordPress uses a maximum of 55 words for the snippet length. Please note, some themes allow you to define this extract via the “personalize” functionality, but others do not allow it and sometimes you still need to personalize this via a piece of code.
Function to customize excerpt length via word count
To increase or decrease the size of this extract, here is a little hack to add to your theme's functions.php file, or via a plugin such as Code Snippets.
function custom_excerpt_length($length) {
return 100; // Change this number to the desired exception length
}
add_filter('excerpt_length', 'custom_excerpt_length', 999);
In this snippet we define a new function called "custom_excerpt_length" which calls the WordPress length function, which defines the length of the excerpt of a WordPress post or page, which we set to "100" words for example , via the “return” instruction, after which we add this new filter with parameter 999 to ensure that it comes after any other possible filter that has a contradictory instruction on the “length” function of the extract.
But be careful, for this to be taken into account on the theme side, make sure that your theme calls the function exception somewhere where you want the article excerpt to appear in your loop, via the code <?php echo get_excerpt(); ?>
There is also another way to customize the length of the excerpt of a WordPress publication, which is based on the number of paragraphs.
Function to customize excerpt length via number of paragraphs
This feature is particularly useful if you want to avoid cutting off a sentence in the middle. To do this, copy and paste this piece of code into your “functions.php” file, or via the Code Snippets extension or any other plugin allowing the addition of PHP functions to your WordPress installation:
add_filter( 'wp_trim_excerpt', 'my_custom_exception', 10, 2 );
function my_custom_exception($text, $raw_excerpt) {
if( ! $raw_excerpt ) {
$content = apply_filters( 'the_content', get_the_content() );
$text = noun( $content, 0, strpos( $content, '</p>' ) + 4 );
}
return $text;
With the wp_trim_excerpt function, WordPress overrides the length of the excerpt in terms of words or characters and considers the first paragraph to be the excerpt, and it even works with Elementor.