WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is it possible to display related posts from same category as the current post?

share|improve this question
up vote 4 down vote accepted

One possibility:

$related = get_posts( array( 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 5, 'post__not_in' => array($post->ID) ) );
if( $related ) foreach( $related as $post ) {
/*whatever you want to output*/

Answe re-written based on WP_Query():

$related = new WP_Query( ( array( 'category__in' => wp_get_post_categories($post->ID), 'posts_per_page' => 5, 'post__not_in' => array($post->ID) ) );
if( $related->have_posts() ) { 
  while( $related->have_posts() ) { $related->the_post(); 
/*whatever you want to output*/
share|improve this answer
Be very careful with your variable names! You're using a global $post to perform your query, then redefining $post in the same context within your foreach loop. – EAMann Oct 2 '11 at 16:15
@EAMann - you are generally right - however in my experience, using setup_postdata() with anything other than $post does not deliver the right output for the_title() for instance. wp_reset_postdata() should in theory take care of resetting $post. – Michael Oct 2 '11 at 17:08
That's because setup_postdata() itself references $post as a global. Instead of using get_posts() you should define a custom instance of WP_Query and use that to get your posts. It will set up the post data for you as well as make the_title() et al work the way they're supposed ti. – EAMann Oct 3 '11 at 1:12
@EAMann This is a rather old post, but it would be appreciated if you could write an answer on how to do that correctly with the custom query and all – GiantCowFilms Nov 25 '15 at 15:47

Your Answer


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.