Modifying WordPress Excerpt Length
Custom Code Solution
This code allows you to change the number of words shown in post excerpts across your entire WordPress site.
Add this code to your theme's functions.php
file:
function custom_excerpt_length( $length ) {
return 25; // Change this number to set your desired excerpt length
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
To also customize the excerpt's ending (replacing the default [...]), add this code:
function custom_excerpt_more( $more ) {
return '...'; // Change this to your desired excerpt ending
}
add_filter( 'excerpt_more', 'custom_excerpt_more' );
For more control over excerpt formatting, here's an advanced version that handles HTML tags and allows character-based limits:
function advanced_custom_excerpt( $text ) {
$raw_excerpt = $text;
// Set your parameters here
$allowed_tags = '<p>,<a>,<em>,<strong>'; // Allowed HTML tags
$excerpt_length = 160; // Character limit
$ending = '...'; // Excerpt ending
$text = strip_shortcodes( $text );
$text = strip_tags( $text, $allowed_tags );
$text = substr( $text, 0, $excerpt_length );
$text = substr( $text, 0, strrpos( $text, ' ' ) );
$text = trim( $text ) . $ending;
return $text;
}
add_filter( 'get_the_excerpt', 'advanced_custom_excerpt' );
Where to Add the Code
- Add the code to your theme's
functions.php
file
- If using a child theme (recommended), add it to the child theme's
functions.php
- Alternative: Create a site-specific plugin
Plugin Solutions
If you prefer using a plugin, here are reliable options:
-
Advanced Excerpt - Offers control over excerpt length, HTML tags, and more
-
Excerpt Editor - Provides a user-friendly interface for excerpt management
Notes
- The default WordPress excerpt length is 55 words
- Custom code solutions work globally across your site
- Numbers in the code examples can be adjusted to match your needs
- Character-based limits (as shown in the advanced example) work better for some languages