What I’m trying to do:
I want to display the_excerpt
, but I have a maximum of x
characters the_excerpt
may use, but I don’t want to display a couple of characters of a word, only whole words.
Some more information:
This code is on a non-single/non-permalink web page such as archives, categories, front page, and searches, that makes me unable to use <!--more-->
.
The code:
This is the code I use:
add_filter( 'excerpt_length', function( ) {
return 20;
} );
if ( have_posts() ):
while( have_posts() ): the_post();
the_excerpt( );
endwhile;
endif;
This should take into account your max length and split the text at the nearest word boundary.
Apply the filter, and call
the_excerpt();
in your templatesApparently there’s a
wp_trim_words
function from WP 3.3 that you can also use, but from the source looks very inefficient. Appart from using 3 regexes, it splits the text into an array of words, and this can get very slow and memory exhaustive for large chunks of text…After some puzzling, I found this solution:
It works! YAY! But since it has to repeatably call
get_the_excerpt
, the page slows down a bit.