Introducing the excerpt_length filter hook

If you notice the above image, the length of the excerpt is too big.

Thankfully, we can reduce the length( number of words ) of the excerpt using the excerpt_length filter hook.

Common, go ahead and paste the following code at the end of the functions.php file:


/*
 * Custom Excerpt Length
 */
function nd_dosth_custom_excerpt_length() {
    return 20;
}
add_filter( 'excerpt_length', 'nd_dosth_custom_excerpt_length' );

In the above code, we are hooking our nd_dosth_custom_excerpt_length filter to the excerpt_length filter hook.

And inside our filter, we are limiting the excerpt length to 20 words. That’s all.

Now, this excerpt length applies all the archives. Not just the blog posts index. 

The excerpt_length filter hook is universal. You’ll know what I mean in a future module.

Anyway, here is how the excerpt looks in the browser.

Neat, right? 

Also, currently, I don’t really like the default […] at the end of the excerpt, I want to remove those brackets by keeping them just the three dots.

To achieve this, we have to use another filter hook called:

excerpt_more

So, put the following code at the end of the functions.php file:


/*
 * Remove brackets at the end of each excerpt
 */
function nd_dosth_custom_excerpt_more() {
    return '...';
}
add_filter( 'excerpt_more', 'nd_dosth_custom_excerpt_more' );

Easy, right?

In the next lesson, we will fix the problem with categories.