0

I want to show excerpt and cap it at 20 words

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 Sep 18 '19 at 19:03
  • I want to show excerpt and cap it at 20 words – Oluwatemitope Adeala Sep 19 '19 at 8:35
1

You 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.

3
  • You may want to explain what to do with this code, for example, It goes in your theme or child theme's functions.php. – RiddleMeThis Sep 18 '19 at 19:28
  • As Tom pointed out, I think I gave the answer to the wrong question. Will leave it here for now and see. – VoidZA Sep 18 '19 at 19:33
  • nah, I think your right. But I guess who knows for sure. Poor question. – RiddleMeThis Sep 18 '19 at 19:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.