Using WordPress ‘exit_on_http_head’ PHP filter

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

Usage

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

Parameters

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

More information

See WordPress Developer Resources: excerpt_length

Examples

Set excerpt length to 20 words

This example changes the maximum number of words in a post excerpt to 20.

function set_excerpt_length_to_20($length) {
    return 20;
}
add_filter('excerpt_length', 'set_excerpt_length_to_20', 999);
// Output: Excerpt will be limited to 20 words.

Double the default excerpt length

This example doubles the default excerpt length to 110 words.

function double_excerpt_length($length) {
    return $length * 2;
}
add_filter('excerpt_length', 'double_excerpt_length', 999);
// Output: Excerpt will be limited to 110 words.

Set excerpt length based on post category

This example sets different excerpt lengths for different post categories.

function category_based_excerpt_length($length) {
    if (in_category('short')) {
        return 30;
    } elseif (in_category('long')) {
        return 100;
    }
    return $length;
}
add_filter('excerpt_length', 'category_based_excerpt_length', 999);
// Output: Excerpt length will vary based on the post's category.

Set a custom excerpt length for specific post ID

This example sets a custom excerpt length of 40 words for a specific post with an ID of 123.

function custom_excerpt_length_for_post($length) {
    global $post;
    if ($post->ID == 123) {
        return 40;
    }
    return $length;
}
add_filter('excerpt_length', 'custom_excerpt_length_for_post', 999);
// Output: Excerpt length for post with ID 123 will be limited to 40 words.

Set excerpt length to the value of a custom field

This example sets the excerpt length based on a custom field named ‘excerpt_length’ attached to the post.

function custom_field_based_excerpt_length($length) {
    global $post;
    $custom_length = get_post_meta($post->ID, 'excerpt_length', true);
    if ($custom_length) {
        return (int) $custom_length;
    }
    return $length;
}
add_filter('excerpt_length', 'custom_field_based_excerpt_length', 999);
// Output: Excerpt length will be set based on the value of the 'excerpt_length' custom field.