How to display related posts from same category?

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

4

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();
}

Reference:

  • get_posts

  • wp_reset_postdata

  • wp_get_post_categories

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*/
    }
    wp_reset_postdata();
}

Leave a Comment