Customizing the WordPress Excerpt Length

Lukas K. Dec 25, 2024 WordPress Excerpt Customization
How can I change the number of words shown in the preview of my blog posts?
What is the best way to programmatically customize the excerpt length in WordPress using the 'excerpt_length' filter?
Andy answered Dec 25, 2024

Custom Code Solution

The simplest way to modify WordPress excerpt length is by using the excerpt_length filter in your theme's functions.php file.

Add this code to change the excerpt length to 25 words:

function custom_excerpt_length( $length ) {
    return 25; // Change this number to adjust excerpt length
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

For more flexibility, you can create a function that allows different lengths based on post type:

function advanced_excerpt_length( $length ) {
    // Get current post type
    $post_type = get_post_type();
    
    // Set different lengths for different post types
    switch ( $post_type ) {
        case 'post':
            return 25; // Regular posts
        case 'page':
            return 35; // Pages
        case 'product':
            return 15; // WooCommerce products
        default:
            return 20; // All other post types
    }
}
add_filter( 'excerpt_length', 'advanced_excerpt_length', 999 );

Where to Place the Code

Add either code snippet to your theme's functions.php file or in a site-specific plugin. For better practice, use a child theme to prevent losing changes during theme updates.

Plugin Solutions

If you prefer a plugin solution, these options are reliable:

  1. Advanced Excerpt - Offers detailed control over excerpt length, allowed tags, and read more text
  2. Excerpt Editor - Provides a simple interface to manage excerpt settings

Additional Tips

  • The priority number (999) ensures your custom length overrides other potential modifications
  • WordPress counts words, not characters
  • This solution works with both automatically generated excerpts and manual excerpts
  • To modify the excerpt's HTML output, use the excerpt_more filter
  • The custom code solution is lighter and more efficient than using a plugin