• Hi

    Have a bit of a brainteaser, wonder if anyone smart enough can help me out; I’ve got a single post page that displays a singe post 🙂

    But underneath I wish to display posts in the same category, I have the code below, which works, HOWEVER 🙂 I want it to exclude the current post AND exclude duplicates of posts, as for example I want to be able to tag a post in multiple categories but other posts might be in multiple categories also, so it might bring in multiple copies of the same post;

    Does that make sense? Hopefully it does

    Thanks for any help

    <?php
    	global $post;
    	$categories = get_the_category();
    	foreach ($categories as $category) :?>
    		<?php
    			$posts = get_posts('numberposts=3&category='. $category->term_id);
    			foreach($posts as $post) : ?>
    
    			<li>
    				<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    			</li>
    
    		<?php endforeach; ?>
    <?php endforeach; ?>
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    You need to progressively build an array of post IDs that is passed as the ‘post__not_in’ argument for each iteration of get_posts(). The first time through, the array only contains the current post ID. As each link is output, add the corresponding ID to the array. Thus the next category query will not have any duplicates from the first category. Rinse and repeat 😉

    You will need to convert your get_posts() arguments to the array format, you cannot mix string and array formats. I always recommend everyone abandon the string in favor of array for all cases. It’s less error prone, easier to read and maintain, and certain query arguments will only work with the array format.

Viewing 1 replies (of 1 total)

The topic ‘Display Posts in same category’ is closed to new replies.