I’m trying to build a theme, I want to control the length of the post excerpts by doing something like this in functions.php:
function theme_excerpt_length( $length ) {
return 45;
}
add_filter( 'excerpt_length', 'theme_excerpt_length', 999 );
But it doesn’t seem to have the desired effect of reducing length of excerpt to 45 words. Even, without the function, some excerpts are longer than the default 55 words. What could be wrong?
The are two quick ways to display custom excerpt lengths in your theme using
wp_trim_words
. Remember, if you usethe_excerpt()
, your excerpt length will always be a maximum of 55, never more. If you usethe_content()
on the other hand, you can specify an excerpt length of more than 55 words.Use the following to display your excerpt. Remember to replace
get_the_excerpt
withget_the_content
if you need an excerpt of more than 55, and replace<a href="'. esc_url( get_permalink() ) . '">' . ' …' . __( 'Read more »', 'pietergoosen' ) . '</a>
with any excerpt ending you need. My ending display a “read more” text with the name of the post.Now just use
echo pietergoosen_custom_excerpts($limit);
anywhere in your templates where you need to display excerpts. Just change$limit
to the actual amount of words, for exampleecho pietergoosen_custom_excerpts(45);
to display 45 wordsEDIT
Have a look at my answer on a custom excerpt as well
This is the function I use for controlling excerpt/content lengths, especially in situations where the end user won’t likely remember to add the
<!--more-->
tag, but the design of the theme requires is.From there, you can change your excerpt code in your template files from:
<?php the_excerpt();?>
…to:
<?php echo excerpt(25);?>
where 25 is the number of characters you want displayed. When designing themes, I tend to stick with characters instead of words because the spacing is a little more consistent.
If you have custom excerpt, the “excrept_lenght” filter will not work for it. You can use this filter to trim custom excerpt.
Good Luck!