Hair Tyson
Its all about Me and My Designs

Archive for the ‘Tips & Tricks’ Category

How To: Avoid Duplicate Posts

Monday, July 20th, 2009

A reader writes in:

I’m developing a new theme and I’m having trouble getting duplicate posts from showing when running two loops (one standard loop and one from a specific category). Even when I copied the specific code from directly from the codex, it was not working.

The Codex article the reader mentioned was regarding the Loop. Although the example shows how to avoid a single duplicate post, it doesn’t show how to avoid duplicating multiple posts.

Here’s how to show two individual loops without duplicating posts in either loop.

Step 1: Add a ‘posts_where’ Function

A WordPress filter is needed to accomplish this, and we’re going to be tapping into the ‘posts_where‘ filter.

The reason being is we need to modify the query used for the loop and exclude some posts.

Here’s the function we’ll be using called post_strip:

function post_strip($where) {
	global $myPosts, $wpdb;
	$where .= " AND $wpdb->posts.ID not in($myPosts) ";
	return $where;
}

In the above code, I use a global variable called $myPosts, which is comma-separated string of post IDs to exclude.

Step 2: Start the First Loop

Within this first loop we’ll be keeping track of the post IDs being used. Nothing fancy is being done here. We’re just pulling the last five posts posted.

<?php
global $myPosts;
$myPosts = '';
?>
<div>
<?php
$my_query = new WP_Query();
$my_query->query('showposts=5');
if ($my_query->have_posts()) : while ($my_query->have_posts()) :
$my_query->the_post(); ?>
<?php $myPosts .= $post->ID . ","; ?>
<div><?php the_title(); ?></div>
<!-- Post Stuff -->
<?php endwhile; endif; ?>
</div>

Pay special attention to the $myPosts variable, which is used to keep track of all of the post IDs. (more…)