Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 3 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 ) {
setup_postdata($post);
/*whatever you want to output*/
}
wp_reset_postdata();

http://codex.wordpress.org/Template_Tags/get_posts http://codex.wordpress.org/Function_Reference/wp_reset_postdata http://codex.wordpress.org/Function_Reference/wp_get_post_categories

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
1  
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

Your Answer

 
discard

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.