DESIGNED DEVELOPED DELIVERED

Mob: 07760 392284edward@ee-web.co.uk

ee-web thinks... a bit

Go on, make my day ... leave a comment

Pagination and Removing Categories in WordPress

October 13th, 2015 by Edward

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.

categories

Edward owns and runs ee-web design and has been building websites for over 12 years. He is passionate about... most things really

Was this post helpful or interesting? Spread the news.

  1. As an extra point I often want to remove posts from several categories:

    so line 3 then becomes:

    category__not_in’=>array(5,3)

    Comment by Edward — October 14, 2015 @ 9:38 am

Leave a comment

*


tag