Wordpress - How to set different posts per page nu

2020-05-09 22:17发布

问题:

On my Wordpress website I have two categories: news and club. How to set number of posts per page to 10 for news category and 4 posts per page for club category?

I have set number of posts per page in Settings > Reading to 10 and news works as I want but not club

I have custom loop in club category where I set posts_per_page to 4. In category-club.php I have

$args=array(
    'category_name'=>'club',
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 4,
    'orderby' => 'date',
    'order' => 'desc',
    'paged' => ((get_query_var('paged')) ? get_query_var('paged') : 1)
  );

But there is problem when I switch to page 2 of posts in this category. I get 404 error. I think it's because I have less than 10 posts in this category.

Can anyone tell me what should I do to get second and next pages work?

回答1:

You shouldn't be running custom queries in place of the main query. They always lead to more issues, and pagination is always one of them as you have experienced. Also, running custom queries in place of the main query slows your page down, so it is always a loose-loose situation.

If you need to change something in the main query, use pre_get_posts to achieve what you need. You can try the following: (Just remember to go back to the default loop in your category pages)

add_action( 'pre_get_posts', function ( $q )
{
    if (    !is_admin() // Only target the frontend
         && $q->is_main_query() // Only target the main query
         && is_category() // Only target category pages
    ) {
        if ( is_category( 'news' ) )
            $q->set( 'posts_per_page', 10 );

        if ( is_category( 'club' ) )   
            $q->set( 'posts_per_page', 4 );
    }
});


标签: php wordpress