Multiple WordPress Queries – Duplicates

You’ve got 2,3,4… custom post queries on a page and you need to get some control over duplicates – it looks unprofessional if your theme keeps showing the same stuff. Let’s take the example of displaying separately posts from 2 different categories – but if a post is in both categories, not duplicated across the lists.

The process is fairly simple:- 2 custom queries, but we catch a list of the post_ids as we loop through the first query, ready for their exclusion from the second.

	// declare the duplicates array - good practice
	$duplicates = array(); 

	$args = array('cat' => '5', 'showposts'=> '10');
	$customQuery = new WP_Query($args);

	if($customQuery->have_posts()){
		while ($customQuery->have_posts()){

			$customQuery->the_post();

			//here's where we catch the ids
			$duplicates[] = $post->ID; 

			//do something with the postdata, display it etc.
		}
	}

The post__not_in parameter of a WP_Query takes an array – which is kinda useful, since an array is just what we’ve got – never say WordPress developers aren’t on the ball…. Don’t forget, it still needs to be an array, even if you’re only passing one value. So if we continue….

	$args = array('cat' => '6', 'showposts'=> '10', 'post__not_in' => $duplicates);
	$customQuery2 = new WP_Query($args);
		if($customQuery2->have_posts()){
	// etc etc

Another obvious application is in displaying a query of featured (category) posts and then not duplicating these posts in the later display of latest posts – a common trope in the average theme index page nowadays…

Share:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • LinkedIn
  • Reddit
  • StumbleUpon
  • RSS
  • Twitter

Trackbacks

  1. WordPressPlanet.com

Leave a Reply