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 -->



2 Answers 2


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,
  • Thanks. Had a feeling it was something like that, i just don't know enough php jargon.
    – Carpy
    Dec 2, 2010 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.

  • This sounds efficient, but i haven't a clue how i'd do it.
    – Carpy
    Dec 2, 2010 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, 2010 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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