0

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

3

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

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.

2
  • This sounds efficient, but i haven't a clue how i'd do it. – Carpy 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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