WordPress如何实现自定义文章显示数量

发布时间:

一般WordPress显示文章数是可以通过在后台阅读设置中指定,后台设置会同步统一应用到首页、列表页、搜索页、标签页和分类页等等。然而我们会遇到根据页面类型指定每页显示文章数,那么如何自定义WordPress文章显示数量?这时候就需要需要我们手动写代码实现了,下面简单介绍下。

WordPress如何实现自定义文章显示数量

1、将下面代码添加到当前主题函数模板functions.php中,最终效果是搜索结果页面显示3篇文章,文章归档页面显示6篇。

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’, +6 );
}
return $query;
}

2、若想实现不同分类显示不同的文章数,修改其中的分类ID,实现指定的分类显示不同的文章数。

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’, 6 );
}
elseif ( ( ! is_admin() ) && ( $query === $GLOBALS[‘wp_the_query’] ) && ( is_category(array(5,6)) ) ) {
$query->set( ‘posts_per_page’, 2 );
}