• Resolved HuntingTown

    (@huntingtown)


    I’m trying to create a related posts section that draws posts from the same categories as the current post. Currently I have this –

    <ul>
    
    		 <?php
    		foreach( ( get_the_category() ) as $category ) {
    		$the_query = new WP_Query('category_name=' . $category->category_nicename . '&showposts=5&order=ASC');
    		while ($the_query->have_posts()) : $the_query->the_post();
    
    		?>
    					<li>
    						<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><div class="rcont_image"><?php the_post_thumbnail( 'medium'); ?></div></a>
    						<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><h6><?php the_title(); ?></h6></a>
    					</li>
    
    		<?php endwhile; ?>
    		<?php
    		}
    		?>
    
    		</ul>

    However this not only returns the current post (which I don’t want) but also returns duplicates for every category attributed to the post.

    For instance, if the current post is in the categories
    -Travel
    -Asia
    -Thailand

    It returns that post three times (one for each category) and similar for any other posts with multiple categories.

    How can I get it to just return a post once?

Viewing 2 replies - 1 through 2 (of 2 total)
  • You can create a ‘$post_not_in’ array and add each ID to it as you display a post:

    while ( have_posts() ) { the_post();
       $post_not_in = array($post->ID);  // Save the current post ID
    
    ?>
    <ul>
    
       <?php
       foreach( ( get_the_category() ) as $category ) {
          $args = array(
             'category_name' => $category->category_nicename,
             'showposts' => 5,
             'order' => 'ASC',
             'post__not_in' => $post_not_in,
          );
          $the_query = new WP_Query($args);
          while ($the_query->have_posts()) : $the_query->the_post();
             $post_not_in[] = $post->ID;
             ?>
             <li>
                <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><div class="rcont_image"><?php the_post_thumbnail( 'medium'); ?></div></a>
                <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><h6><?php the_title(); ?></h6></a>
             </li>
    
          <?php endwhile; ?>
          <?php
       }
       ?>
    
    </ul>
    Thread Starter HuntingTown

    (@huntingtown)

    You are a scholar and a king among men. That worked a treat ??

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to Avoid Duplicates when Post is from Multiple Categories?’ is closed to new replies.