K
K
kopvi642021-12-10 13:33:03
WordPress
kopvi64, 2021-12-10 13:33:03

How to paginate a specific category?

Good day!

With the help of this code, I display the latest paginated posts in WordPress:

<?php
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
get_template_part( 'template-parts/content-my', get_post_type() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content-my', 'none' );
endif;
?>

Everything works well, the first page displays as many news as I set in the WordPress reading settings (4) and the second page 3, for a total of 7 news.

But the problem is that I have to add "query_posts('cat=2');" after "if ( have_posts() ) :" to display news of only a certain category, then pagination stops working correctly. Instead of displaying 4 posts on the first page and 2 posts on the second (total 6 news in this category), we get 4 latest news on the first page and the same 4 latest news on the second page.

I can't figure out what the problem

is Thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
altkov, 2021-12-10
@kopvi64

Add a paged filter to query_posts and set it to get_query_var('paged')

A
Artem Zolin, 2021-12-10
@artzolin

You can't use query_posts(), it's a kernel system function, you'll break the main query. To fix it, use the hookpre_get_posts

add_action( 'pre_get_posts', 'set_front_page_category' );
function set_front_page_category( $query ) {
  if ( $query->is_front_page() && $query->is_main_query() ) {
    $query->set( 'cat', '2' );
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question