WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using this piece of code to show related posts based on the tag of the post you are viewing.

I'd like to modify is a little to exclude the related posts from the loop if they are in the same category of the post you are viewing

Reason for this is i already have a loop to show related posts in the same category, so trying to cut out the duplicates.

$tags = wp_get_post_tags($post->ID);
if ($tags) {
  $first_tag = $tags[0]->term_id;
    'tag__in' => array($first_tag),
    'post__not_in' => array($post->ID),
  $my_query = new WP_Query($args);
  if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>

        <!-- loop here -->



share|improve this question
up vote 3 down vote accepted

Very similar to what you do with tags. Retrieve IDs of categories for current post:

$categories = get_the_category();
$cat_ids = array();
foreach($categories as $category)
    $cat_ids[] = $category->term_id;

Then exclude them in query:

'category__not_in' => $cat_ids,
share|improve this answer
Thanks. Had a feeling it was something like that, i just don't know enough php jargon. – Blackbird Dec 2 '10 at 12:43

What you can also do is keep a global variable that contains all post id's that you already showed in a "related articles" area, and pass that to post__not_in. This allows you to add and remove other ways to show related articles (by enabling or disabling widgets?), and always prevent duplicates.

share|improve this answer
This sounds efficient, but i haven't a clue how i'd do it. – Blackbird Dec 2 '10 at 12:43
@Blackbird: Very easy: when you loop to display each related item, add a line like $wpse4770_displayed_related_post_ids[] = get_the_ID(); and pass that array to your post__not_in query argument. – Jan Fabry Dec 2 '10 at 13:33

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.