Wordpress get_posts without the current post

Displaying links to other articles of the same category is pretty easy in Wordpress. get_posts function accept a category parameter. So you can use

global $post;
$categories = get_the_category();
foreach ($categories as $category) :
?>
 
	<?php
	$posts = get_posts('numberposts=5&category='. $category->term_id);
	$i=0;
	foreach($posts as $post) :
 
	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
 
	<?php
	endforeach; 
 
endforeach;

to get the the latest five post of the current category.

If the current posts one of the latest five, you can sort it out in this way:

Update: Read update below!

global $post;
$categories = get_the_category();
foreach ($categories as $category) :
?>
 
	<?php
	$this_single_id = get_the_ID();
	$posts = get_posts('numberposts=5&category='. $category->term_id);
	$i=0;
	foreach($posts as $post) :
 
	if ($this_single_id == $post->ID)
		continue;
 
	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
 
	<?php
	endforeach; 
 
endforeach;

Note: With this apprach only four links are displayed if the current post is one of the latest five. If you want to disyplay five links in any case, you have to request six posts (numberposts=6) skipping the last one if the current post was not found before.

Update: I missed the $exclude parameter. You can simply use it in your get_posts request in order to exclude the current post. Use this instead of the approach above.

Leave a Reply