Using WordPress ‘excerpt_length’ PHP filter

The excerpt_length WordPress PHP filter allows you to modify the maximum number of words in a post excerpt.

Usage

function custom_excerpt_length( $length ) {
    // your custom code here
    return $length;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 10, 1 );

Parameters

  • $length (int): The maximum number of words in the excerpt. Default is 55.

More information

See WordPress Developer Resources: excerpt_length

Examples

Change excerpt length to 20 words

Set the post excerpt length to 20 words.

function mytheme_custom_excerpt_length( $length ) {
    return 20;
}
add_filter( 'excerpt_length', 'mytheme_custom_excerpt_length', 999 );

Double the excerpt length

Double the default excerpt length (110 words).

function double_excerpt_length( $length ) {
    return $length * 2;
}
add_filter( 'excerpt_length', 'double_excerpt_length', 10, 1 );

Set a specific excerpt length for a category

Set the excerpt length to 30 words for posts in the “news” category.

function news_excerpt_length( $length ) {
    if ( in_category( 'news' ) ) {
        return 30;
    }
    return $length;
}
add_filter( 'excerpt_length', 'news_excerpt_length', 10, 1 );

Set different excerpt lengths based on post type

Set excerpt length to 75 words for “page” post type and 40 words for “post” post type.

function post_type_excerpt_length( $length ) {
    if ( get_post_type() == 'page' ) {
        return 75;
    } elseif ( get_post_type() == 'post' ) {
        return 40;
    }
    return $length;
}
add_filter( 'excerpt_length', 'post_type_excerpt_length', 10, 1 );

Set excerpt length based on the number of posts

Increase the excerpt length by 5 words for every 3 posts.

function dynamic_excerpt_length( $length ) {
    global $wp_query;
    $current_post = $wp_query->current_post;
    $extra_words = floor( $current_post / 3 ) * 5;
    return $length + $extra_words;
}
add_filter( 'excerpt_length', 'dynamic_excerpt_length', 10, 1 );