Customize The Excerpt Length in WordPress Using PHP

By: Bobby

Published on: Aug 12, 2022

< 1 min read.

If you just dabble in WordPress development even the slightest bit, you know about the famous the_excerpt(); function in WordPress core. If you aren’t familiar, the function simply returns a shorten string of the content for the current post or page. The string is stripped of all html tags or styling. Great for creating post feeds in your theme!

This function is very handy, but it is limiting. By default, the length of the excerpt is set to 55 words. This can easily be changed to any length you desire by placing the following function in your theme’s functions.php file:

/**
 * Filter the except length to 20 words.
 *
 * @param int $length Excerpt length.
 * @return int (Maybe) modified excerpt length.
 */
function wpdocs_custom_excerpt_length( $length ) {
    return 20;
}
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );

Simple right? This is nice for getting it where you want it, but you’re still limited to whatever the new limit is. What if you need it to be 20 words on your blog’s feed, and 75 words on your events feed?

Well, here is a simple function that will do just that! The idea is simple. Inside of your post loop, instead of calling the_excerpt();, you can make this call instead:

get_the_content(); grabs the post’s content (tags and all) in a php variable we can pass to our custom function. Just output the returned string and you’re done!