注意excerpt_length
过滤器不是这样工作的。它需要一个参数,$length
, 这是摘录的字长。
更新的解决方案首先连接回调函数wpse_default_excerpt_length()
到excerpt_length
滤器这是默认的摘录长度处理程序。
接下来,一些额外的excerpt_length
回调函数是声明的,但我们不会将它们连接到这里。相反,这将在自定义查询本身中处理(请参阅下面的home.php部分)。
functions.php
/**
* Set the excerpt lengths for the **main** query.
*
* @param int $length Excerpt length.
* @return int
*/
add_filter( \'excerpt_length\', \'wpse_default_excerpt_length\', 100 );
function wpse_default_excerpt_length( $length ) {
global $wp_query;
// If we\'re on the first post of the first page of posts:
if ( $wp_query->current_post == 0 && ! $wp_query->is_paged ) {
$length = 55;
} else { // All other posts:
$length = 20;
}
return $length;
}
/**
* Set the excerpt lengths for a custom query - first post.
*/
function wpse_custom_loop_intro_excerpt_length( $length ) {
return 60;
}
/**
* Set the excerpt lengths for a custom query - other posts.
*/
function wpse_custom_loop_excerpt_length( $length ) {
return 30;
}
home.php
<div class="section-content section-news-content">
<?php
$args = [
\'posts_per_page\' => 5,
\'post_type\' => \'post\',
\'cat\' => 2,
];
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// If we\'re on the first post of the first page of posts:
if ( $query->current_post == 0 && ! $query->is_paged ) {
// Add our particular excerpt_length filter. Note that at priority 200,
// it will override wpse_default_excerpt_length() at priority 100
add_filter( \'excerpt_length\', \'wpse_custom_loop_intro_excerpt_length\', 200 );
get_template_part( \'template-parts/content\', \'news\' );
// Clean up after ourselves.
remove_filter( \'excerpt_length\', \'wpse_custom_loop_intro_excerpt_length\', 200 );
} else { // All other posts in this custom loop:
add_filter( \'excerpt_length\', \'wpse_custom_loop_excerpt_length\', 200 );
get_template_part( \'template-parts/content\', \'news\' );
remove_filter( \'excerpt_length\', \'wpse_custom_loop_excerpt_length\', 200 );
}
}
wp_reset_postdata();
}
?>
</div>
content-news.php
控制摘录长度是通过
excerpt_length
以前添加的筛选器。使用
the_excerpt()
输出摘录。
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="excerpts">
<div class="post-text">
<div class="entry-content">
<span class="entry-text"><?php the_excerpt(); ?></span>
</div><!-- .entry-content -->
</div>
</div>
</article>