WordPress Pagination: How to Make it Work
Posted: May 6th, 2015 | Author: Julia | Filed under: Development, Tips and Tricks | Tags: next_posts_link, number of posts, pagination, previous_posts_link, WordPress | 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
-
<?php next_posts_link(); ?>
-
<?php previous_posts_link(); ?>
And usually you work with the pagination such way:
-
<?php if (have_posts()) : ?>
-
<?php while (have_posts()) : the_post(); ?>
-
<?php the_content(); ?>
-
<?php endwhile; ?>
-
<?php next_posts_link('« Older Entries') ?>
-
<?php previous_posts_link('Newer Entries »') ?>
-
<?php else : ?>
-
<p>Page 404</p>
-
<?php endif; ?>
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:
-
<?php query_posts( array(
-
'cat' => 42, //my specific category
-
'posts_per_page' => 4 //number of posts per page
-
)); ?>
-
<?php if (have_posts()) : ?>
-
<?php while (have_posts()) : the_post(); ?>
-
-
<div class="eight columns">
-
<article>
-
<header>
-
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
-
</header>
-
<?php the_content(); ?>
-
</article>
-
</div>
-
<?php endwhile;?>
-
<div class="navigation">
-
<?php next_posts_link('« Older Entries') ?>
-
<?php previous_posts_link('Newer Entries »') ?>
-
</div>
-
<?php else : ?>
-
<p>Page 404</p>
-
<?php endif; wp_reset_query(); ?>
The solution for me is to replace query_posts:
-
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
-
$args= array(
-
'posts_per_page' =>4,
-
'cat' => 42,
-
'paged' => $paged
-
);
-
query_posts($args);
-
?>
-
<?php if (have_posts()) : ?>
-
<?php while (have_posts()) : the_post(); ?>
-
-
<div class="eight columns">
-
<article>
-
<header>
-
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
-
</header>
-
<?php the_content(); ?>
-
</article>
-
</div>
-
<?php endwhile;?>
-
<div class="navigation">
-
<?php next_posts_link('« Older Entries') ?>
-
<?php previous_posts_link('Newer Entries »') ?>
-
</div>
-
<?php else : ?>
-
<p>Page 404</p>
-
<?php endif; wp_reset_query(); ?>
And now it works like a charm ))
Leave a Reply