Customizing WordPress Excerpt Length
Custom Code Solution
To modify the excerpt length, you can use WordPress's built-in excerpt_length
filter. Place this code in your theme's functions.php
file:
This code changes the excerpt length to 25 words:
function custom_excerpt_length($length) {
return 25; // Change this number to adjust word count
}
add_filter('excerpt_length', 'custom_excerpt_length', 999);
To also customize the excerpt's ending (replace default [...]):
function custom_excerpt_more($more) {
return '...'; // Change this to your preferred ending
}
add_filter('excerpt_more', 'custom_excerpt_more');
For more control over the excerpt formatting and HTML tags:
function custom_formatted_excerpt($text) {
$raw_excerpt = $text;
if ('' == $text) {
$text = get_the_content('');
$text = strip_shortcodes($text);
$text = excerpt_remove_blocks($text);
$text = strip_tags($text);
// Set your word count here
$excerpt_length = 25;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length) {
array_pop($words);
$text = implode(' ', $words);
$text .= '...'; // Custom ending
}
}
return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_formatted_excerpt');
Plugin Solutions
If you prefer a plugin solution, here are reliable options:
-
Advanced Excerpt - Offers control over excerpt length, allowed tags, and custom endings
-
Excerpt Editor - Provides a visual editor for excerpts with length control
SEO Benefits
- Custom excerpt lengths help maintain consistent preview lengths across your site
- Well-formatted excerpts improve click-through rates from search results
- Ideal excerpt length (typically 150-160 characters) helps prevent truncation in search results
Best Practices
- Keep excerpts between 15-25 words for blog listings
- Ensure excerpts contain relevant keywords
- Use clear ending indicators
- Test different lengths for your specific theme layout
- Consider mobile viewing experience when setting length
The custom code solution is preferred as it:
- Reduces plugin overhead
- Offers precise control
- Maintains consistent functionality across theme changes
- Can be easily modified for specific needs