wordpress知识库
网站首页 > 知识库 > wordpress知识 >

wordpress不同的分类使用不同的分页数量

2014/07/28

要在WordPress中为不同的分类使用不同的分页数量,可以使用pre_get_posts钩子来修改每个分类的查询参数。通过检查当前查询是否为分类页面,并根据分类ID设置不同的posts_per_page参数,可以实现这个需求。

以下是一个示例代码,展示如何为不同的分类设置不同的分页数量:

function custom_category_pagination( $query ) {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }

    if ( $query->is_category() ) {
        $category_id = $query->get_queried_object_id();

        // 根据分类ID设置不同的分页数量
        if ( $category_id == 1 ) {
            $query->set( 'posts_per_page', 10 ); // 分类ID为1的分页数量为10
        } elseif ( $category_id == 2 ) {
            $query->set( 'posts_per_page', 15 ); // 分类ID为2的分页数量为15
        } else {
            $query->set( 'posts_per_page', 5 ); // 其他分类的默认分页数量为5
        }
    }
}
add_action( 'pre_get_posts', 'custom_category_pagination' );

上述示例代码将custom_category_pagination函数与pre_get_posts钩子关联,该函数会检查当前查询是否为分类页面,并根据分类ID设置不同的posts_per_page参数。

在示例代码中,我们根据分类ID设置了不同的分页数量。可以根据自己的需求和分类设置相应的分页数量。

将上述代码添加到主题的functions.php文件中,或使用一个自定义wordpress插件来添加这个功能。确保在修改查询参数时,仅对需要修改的查询进行修改,并进行适当的条件检查,以避免意外结果。