WordPress 根据页面类型设置每页显示的文章数

WordPress每页显示的文章数在后台设置中指定,会应用到列表页(通常是首页)、搜索页、标签页、分类页以及时间索引页面:

但有时候我们希望根据不同页面来指定这个数值,使用下面的函数,放在主题 functions.php 函数中即可。

// 根据页面类型指定每页显示的文章数
function custom_posts_per_page($query)
{
    if (is_home()) {
        $query->set('posts_per_page', 8); //首页每页显示8篇文章
    }
    if (is_search()) {
        $query->set('posts_per_page', -1); //搜索页显示所有匹配的文章,不分页
    }
    if (is_archive()) {
        $query->set('posts_per_page', 25); //archive每页显示25篇文章
    }
    if (is_tax('products_list')) {
        $query->set('posts_per_page', 1);
    }
}
//this adds the function above to the 'pre_get_posts' action
add_action('pre_get_posts', 'custom_posts_per_page');