WordPress – How to do Pagination on Category Page

WordPress – How to do Pagination on Category Page

WordPress pagination on category pages can be a bit tricky. This post is assuming your are building a custom category page, like category.php in your theme file.

To start off, we must find the current category of the page (This would vary depending on which category the user clicked on to get to this page). In order to do this insert the following code into your code editor:

  $currCat = get_category(get_query_var('cat'));
  $cat_name = $currCat->name;
  $cat_id   = get_cat_ID( $cat_name );

Now that we have the current category saved in $cat_id, it is time for the second part, which sets specific arguments for your loop and the actual loop itself. NOTE: Do not put an offset number into the loop or it will break.

  $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
  $temp = $wp_query;
  $wp_query = null;
  $wp_query = new WP_Query();
  while ($wp_query->have_posts()) : $wp_query->the_post();

After that code is where you can put in your HTML for the output of your loop. Something like…

  <div class="module-container">;
    <div class="content">;
      <span class="author"><?php the_author(); ?></span>
      <?php the_content(); ?>

That was just a random example of something that your code might look like. It is most likely a bit more complex than that. Anyways, once all that HTML/PHP is done, you need to end the loop.

  <?php endwhile; ?>

After you end the loop, it is time for the final part. This will bring it all together and actually output the pagination links onto the page. You do not need to wrap this code in a div, but I just did it for styling purposes. Also, note than you can change the prev_text and next_text to whatever you want it to say.

  global $wp_query;

  $big = 999999999; // need an unlikely integer
  echo '<div class="paginate-links">';
    echo paginate_links( array(
	'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
	'format' => '?paged=%#%',
	'prev_text' => __('<<'),
	'next_text' => __('>>'),
	'current' => max( 1, get_query_var('paged') ),
	'total' => $wp_query->max_num_pages
    ) );
  echo '</div>';

And there you have it. You just put pagination into your custom category page! Have anything to add? Put it in the comments below.