excerpt_length
Allows changing the maximum number of words in an automatically generated post excerpt. The default is 55 words.
The filter does not limit an excerpt entered manually by the user.
Use the excerpt_more filter to change the text at the end of a trimmed excerpt.
Usage
add_filter( 'excerpt_length', 'wp_kama_excerpt_length_filter' );
/**
* Function for `excerpt_length` filter-hook.
*
* @param int $number The maximum number of words.
*
* @return int
*/
function wp_kama_excerpt_length_filter( $number ){
// filter...
return $number;
}
- $number(int)
- Maximum number of words. Defaults to
55.
Examples
#1 Limit an excerpt to 20 words
add_filter( 'excerpt_length', 'wp_kama_excerpt_length', 999 );
function wp_kama_excerpt_length( $number ) {
return 20;
}
A high priority is needed if a theme or plugin changes the excerpt length after this filter.
#2 Change the length only on the front end
add_filter( 'excerpt_length', 'wp_kama_frontend_excerpt_length', 999 );
function wp_kama_frontend_excerpt_length( $number ) {
if ( is_admin() ) {
return $number;
}
return 30;
}
#3 Set a different length depending on the page
add_filter( 'excerpt_length', 'wp_kama_conditional_excerpt_length', 999 );
function wp_kama_conditional_excerpt_length( $number ) {
if ( is_page_template( 'page-templates/services.php' ) ) {
return 30;
}
if ( is_front_page() && is_home() ) {
return 80;
}
return $number;
}
#4 Get the length from a theme setting
add_filter( 'excerpt_length', 'wp_kama_theme_excerpt_length', 999 );
function wp_kama_theme_excerpt_length( $number ) {
$custom_length = get_theme_mod( 'custom_excerpt_length' );
if ( ! $custom_length ) {
return $number;
}
return absint( $custom_length );
}Changelog
| Since 2.7.0 | Introduced. |
Where the hook is called
excerpt_length
wp-includes/formatting.php 4081
$excerpt_length = (int) apply_filters( 'excerpt_length', $excerpt_length );
wp-includes/blocks/latest-posts.php 167
$excerpt_length = (int) apply_filters( 'excerpt_length', $block_core_latest_posts_excerpt_length );
Where the hook is used in WordPress
wp-includes/blocks/latest-posts.php 231
remove_filter( 'excerpt_length', 'block_core_latest_posts_get_excerpt_length', 20 );
wp-includes/blocks/latest-posts.php 59
add_filter( 'excerpt_length', 'block_core_latest_posts_get_excerpt_length', 20 );
wp-includes/blocks/post-excerpt.php 116
add_filter( 'excerpt_length', 'block_core_post_excerpt_excerpt_length', PHP_INT_MAX );
wp-includes/blocks/post-excerpt.php 53
add_filter( 'excerpt_length', 'block_core_post_excerpt_excerpt_length', PHP_INT_MAX );
wp-includes/blocks/post-excerpt.php 57
remove_filter( 'excerpt_length', 'block_core_post_excerpt_excerpt_length', PHP_INT_MAX );