WordPress post excerpts are a great way to quickly present the content to the readers without having them check the entire article to know what it is about. By default, WordPress sets the Excerpt length to 55 words. In most cases, it will be enough and suitable for almost any kind of website. But for some, it can be a bit too long or a bit too short. So, if you want to make changes to the default excerpt length WordPress shows by default, you can change it using the following code.
Usage
- To limit or increase the length of the short content displayed on the website to provide a better user experience.
- To avoid duplicate content issues on websites that publish smaller content and indexes archive pages.
- For magazine websites with a lot of articles and want to keep the space consumed by posts to the minimum by only displaying the necessary information such as the post title, thumbnail, category, etc.
Code
// Change WordPress excerpt length to 25 words
function wpt_change_excerpt_length( $length ) {
return 25; // change 25 to your choice
}
add_filter( 'excerpt_length', 'wpt_change_excerpt_length', 9999);
You can either increase the limit or decrease it. It is upto you. But do not increase it too much in case your content is very short (such as news websites).
Explanation
- Just the comment. You may remove it if you don’t need it.
- Declaring the
wpt_change_excerpt_length
function and passing the$length
argument which will define our excerpt length. - Returning a value to the
$length
attribute to pass to theexcerpt_length
hook. The words after the // is a comment which you can keep or remove if you do not want it. - Just closing the function.
- Adding a filter to the
excerpt_length
function with our newly created functionwpt_change_excerpt_length
and setting the priority9999
so that the filter will be applied late without interfering with other important executions.