excerpt_length
云策文档标注
概述
excerpt_length 是一个 WordPress 过滤器,用于控制文章摘要的最大单词数。开发者可以通过添加自定义函数来修改默认的 55 个单词限制,以适应不同主题或页面的需求。
关键要点
- excerpt_length 过滤器允许修改文章摘要的单词数量,默认值为 55。
- 使用 add_filter 函数添加回调函数,并设置高优先级(如 999)以确保自定义设置不被 WordPress 默认过滤器覆盖。
- 回调函数应返回一个整数,表示期望的摘要单词数。
- 可以结合条件语句(如 is_admin()、is_front_page())实现不同场景下的动态长度调整。
代码示例
function mytheme_custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'mytheme_custom_excerpt_length', 999 );注意事项
- 确保设置正确的优先级,避免默认过滤器覆盖自定义设置。
- 在函数中可添加条件逻辑,例如仅在非管理界面应用修改,或根据页面类型调整长度。
原文内容
Filters the maximum number of words in a post excerpt.
Parameters
$numberint-
The maximum number of words. Default 55.
Source
$excerpt_length = (int) apply_filters( 'excerpt_length', $excerpt_length );
Changelog
| Version | Description |
|---|---|
| 2.7.0 | Introduced. |
Skip to note 6 content
Karmegaraja Subramaniam
/** * Filter the excerpt length to 50 words. * * @param int $length Excerpt length. * @return int (Maybe) modified excerpt length. */ function theme_slug_excerpt_length( $length ) { if ( is_admin() ) { return $length; } return 50; } add_filter( 'excerpt_length', 'theme_slug_excerpt_length', 999 );This will help to apply the excerpt_length on front end only.
Skip to note 7 content
acosmin
Set the excerpt length based on a theme mod, through the Customizer.
function prefix_custom_excerpt_length( $length ) { $custom = get_theme_mod( 'custom_excerpt_length' ); if ( '' !== $custom ) { return absint( $custom ); } else { return $length; } } add_filter( 'excerpt_length', 'prefix_custom_excerpt_length', 999 );Skip to note 8 content
prashaddey
/** * Filter the excerpt length to 20 words. * * @param int $length Excerpt length. * @return int (Maybe) modified excerpt length. */ add_filter( 'excerpt_length', function( $length ) { return 20; } );Skip to note 9 content
Metallicarosetail
/** * Filter the excerpt length to 30 words. * * @param int $length Excerpt length. * @return int (Maybe) modified excerpt length. */ function wp_example_excerpt_length( $length ) { return 30; } add_filter( 'excerpt_length', 'wp_example_excerpt_length');Notes: This will display your excerpt text up to 30 words using excerpt_length filter. By default the number of words is 55.
Example:-
This will display your post excerpt up to 30 words.
Skip to note 10 content
Deepak Rajpal
/** * Filter the excerpt length to 80 words on homepage and 50 words on page template * * @param int $length Excerpt length. * @return int modified excerpt length. */ function wpdocs_custom_excerpt_length( $length ) { if ( is_page_template( 'page-templates/services-page.php' ) ) { return 50; } else if ( is_front_page() && is_home() ) { return 80; } else { return $length; } } add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );This is useful to display different excerpt length on homepage, custom page template (where listing some custom post types).