一般我们都在设置 → 阅读 → 博客页面至多显示中,统一设置每个页面的文章显示数量,如果想某些页面自定义显示数量,不受这个控制,可以通过下面的代码实现。文章源自知更鸟-https://zmingcx.com/wordpress-change-posts-per-page-count.html
将下面代码添加到当前主题函数模板functions.php中:文章源自知更鸟-https://zmingcx.com/wordpress-change-posts-per-page-count.html
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篇。文章源自知更鸟-https://zmingcx.com/wordpress-change-posts-per-page-count.html
如想实现不同分类显示不同的文章数,稍微改一下:文章源自知更鸟-https://zmingcx.com/wordpress-change-posts-per-page-count.html
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,实现指定的分类显示不同的文章数文章源自知更鸟-https://zmingcx.com/wordpress-change-posts-per-page-count.html
文章源自知更鸟-https://zmingcx.com/wordpress-change-posts-per-page-count.html

2021年11月15日 10点57分 1F
又挖掘到新知识啦
2021年11月15日 22点04分 B1
@ 欧乐安 这个新知识是10年前的
2021年11月16日 11点55分 B2
@ 知更鸟
旧知新用