Custom code for modifying the WordPress excerpt length

Laura J Dec 18, 2024 Content Management
How can I change how much of my post shows up in the previews on my site?
What code can I use to filter the excerpt length in WordPress globally using the excerpt_length filter hook?
Andy answered Dec 18, 2024

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

  1. Add the code to your theme's functions.php file
  2. If using a child theme (recommended), add it to the child theme's functions.php
  3. Alternative: Create a site-specific plugin

Plugin Solutions

If you prefer using a plugin, here are reliable options:

  1. Advanced Excerpt - Offers control over excerpt length, HTML tags, and more
  2. 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