About design and nearby

WordPress Pagination: How to Make it Work

Posted: May 6th, 2015 | Author: | Filed under: Development, Tips and Tricks | Tags: , , , , | No Comments »

Function next_posts_link/ previous_posts_link prints a link to the next/ previous set of posts within the current query. It default usage is

  1. <?php next_posts_link(); ?>
  2. <?php previous_posts_link(); ?>

And usually you work with the pagination such way:

  1. <?php if (have_posts()) : ?>
  2. <?php while (have_posts()) : the_post(); ?>
  3. <?php the_content(); ?>
  4. <?php endwhile; ?>
  5. <?php next_posts_link('&laquo; Older Entries') ?>
  6. <?php previous_posts_link('Newer Entries &raquo;') ?>
  7. <?php else : ?>
  8. <p>Page 404</p>
  9. <?php endif; ?>

wordpress pagination

The tricky part comes if you need to print certain number of posts and keep the pagination.


The code below shows properly the first 4 posts from category, but then when you click ‘Older Entries’ link, it displays the same first post again even if the address changes correctly to /wordpress/pagename/page/2 etc:

  1. <?php query_posts( array(
  2. 'cat' => 42, //my specific category
  3. 'posts_per_page' => 4 //number of posts per page
  4. )); ?>
  5.  <?php if (have_posts()) : ?>
  6.  <?php while (have_posts()) : the_post(); ?>
  7.    
  8.  <div class="eight columns">
  9.   <article>    
  10.    <header>
  11.     <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>      
  12.    </header>
  13.    <?php the_content(); ?>
  14.   </article>
  15.  </div>
  16. <?php endwhile;?>
  17. <div class="navigation">
  18.  <?php next_posts_link('&laquo; Older Entries') ?>
  19.  <?php previous_posts_link('Newer Entries &raquo;') ?>
  20. </div>  
  21. <?php else : ?>
  22.  <p>Page 404</p>
  23. <?php endif; wp_reset_query(); ?>

The solution for me is to replace query_posts:

  1. <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
  2. $args= array(
  3. 'posts_per_page' =>4,
  4. 'cat' => 42,
  5. 'paged' => $paged
  6. );
  7. query_posts($args);
  8. ?>
  9.  <?php if (have_posts()) : ?>
  10.  <?php while (have_posts()) : the_post(); ?>
  11.    
  12.  <div class="eight columns">
  13.   <article>    
  14.    <header>
  15.     <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>      
  16.    </header>
  17.    <?php the_content(); ?>
  18.   </article>
  19.  </div>
  20. <?php endwhile;?>
  21. <div class="navigation">
  22.  <?php next_posts_link('&laquo; Older Entries') ?>
  23.  <?php previous_posts_link('Newer Entries &raquo;') ?>
  24. </div>  
  25. <?php else : ?>
  26.  <p>Page 404</p>
  27. <?php endif; wp_reset_query(); ?>

And now it works like a charm ))

Share Button

Check Related Posts:


Leave a Reply


  • 1 × two =

Looking for a Freelance UX & UI designer for your project? I’m ready to jump onboard!

Let's discuss your project now