I want to show excerpt and cap it at 20 words
This question already has answers here: How can i limit the character length in excerpt? [duplicate] (2 answers) Custom Excerpt is returning 52 characters and not 52 words (2 answers) Closed 5 years ago.I want to show excerpt and cap it at 20 words
Share Improve this question edited Sep 19, 2019 at 8:37 Oluwatemitope Adeala asked Sep 18, 2019 at 18:38 Oluwatemitope AdealaOluwatemitope Adeala 12 bronze badges 2- Are you sure you want nothing less than 20 words on the frontpage? Nothing less than 20 words means you only want posts that have more than 20 words. are you sure you don't mean you want to show the excerpt and cap it at 20 words? I would avoid using the phrase "nothing less than" in the future as it's confusing – Tom J Nowell ♦ Commented Sep 18, 2019 at 19:03
- I want to show excerpt and cap it at 20 words – Oluwatemitope Adeala Commented Sep 19, 2019 at 8:35
1 Answer
Reset to default 1You can use filters to change the excerpt length. (It goes in your theme or child theme's functions.php)
function wpdocs_custom_excerpt_length( $length ) {
return 70;
}
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );
At this point I usually also like to change the part that gets added to the end of a truncated excerpt to something like '...'
function wpdocs_excerpt_more( $more ) {
return '...';
}
add_filter( 'excerpt_more', 'wpdocs_excerpt_more' );
If you want this to only happen on your homepage, you can use the is_page(title/slug/id) function as follows:
function wpdocs_custom_excerpt_length( $length ) {
return 70;
}
function wpdocs_excerpt_more( $more ) {
return '...';
}
function homepageCustomExcerpt() {
if (is_page('home')) {
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );
add_filter( 'excerpt_more', 'wpdocs_excerpt_more' );
}
}
add_action( 'init', 'homepageCustomExcerpt' );
The reason for calling the homepageCustomExcerpt
function with add_action( 'init', 'homepageCustomExcerpt' )
is because if is_page()
fires too early, the page would not yet be set and it will always return false.