Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

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

        <!-- loop here -->

      <?php
    endwhile;
  }wp_reset_query();
}
?>

Thanks

share|improve this question
add comment

2 Answers

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

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

Your Answer

 
discard

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.