Quite often I need to create a new WordPress query – but this can mess up the pagination – so that if you press to go to previous posts it shows the same darn posts again.
Thankfully, it’s relatively easy to solve.
I find that I nearly always need to exclude categories from my query so I am adding that in as well.
Here’s the standard code from index.php file int he 2013 template:
<?php if ( have_posts() ) : ?> <?php /* The loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?>
Nothing out of the ordinary there of course.
Firstly we need to add this line:
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$paged is set to the current page that we are looking at – so for example if you are display post 11-20 then its likely that this is page 2 if you have the number of posts per page set to 10.
Next we create a new wordpress query in array format:
$query = new WP_Query( array( 'posts_per_page' => 10, 'cat'=>-145, 'paged'=>$paged ) ); ?>
we create a new WP_Query object called $query
- set the number of posts_per_page to 10 in this case
- set the categories variable to not show cat id =145 – done by setting the minus sign
- and set the paged variable to the $paged we set up before
And hopefully that’s it.