一般我们都在设置 → 阅读 → 博客页面至多显示中,统一设置每个页面的文章显示数量,如果想某些页面自定义显示数量,不受这个控制,可以通过下面的代码实现。
![自定义 WordPress 文章显示数量](https://img-blog.csdnimg.cn/8aa57d2725c24eee83fc4105c7449879.png)
将下面代码添加到当前主题函数模板functions.php中:
add_action( 'pre_get_posts', 'zm_set_posts_per_page' );
function zm_set_posts_per_page( $query ) {
if ( ( ! is_admin() ) && ( $query === $GLOBALS['wp_query'] ) && ( $query->is_search() ) ) {
$query->set( 'posts_per_page', 3 );
}
elseif ( ( ! is_admin() ) && ( $query === $GLOBALS['wp_the_query'] ) && ( $query->is_archive() ) ) {
$query->set( 'posts_per_page', 5 );
}
return $query;
}
上面代码最终效果是搜索结果页面显示3篇文章,文章归档页面显示5篇。
如想实现不同分类显示不同的文章数,稍微改一下:
add_action( 'pre_get_posts', 'zm_set_posts_per_page' );
function zm_set_posts_per_page( $query ) {
if ( ( ! is_admin() ) && ( $query === $GLOBALS['wp_the_query'] ) && ( is_category(array(1,2)) ) ) {
$query->set( 'posts_per_page', 3 );
}
elseif ( ( ! is_admin() ) && ( $query === $GLOBALS['wp_the_query'] ) && ( is_category(array(3,4)) ) ) {
$query->set( 'posts_per_page', 5 );
}
elseif ( ( ! is_admin() ) && ( $query === $GLOBALS['wp_the_query'] ) && ( is_category(array(5,6)) ) ) {
$query->set( 'posts_per_page', 2 );
}
}
修改其中的分类ID,实现指定的分类显示不同的文章数