Simple WordPress Related Posts

Create a simple Related Posts loop based on the current post’s categories.

$post_cats = wp_get_post_categories($post->ID);
$this_post = array($post->ID);
$query_cats = array();
foreach ($post_cats as $cat) $query_cats[] = $cat;

global $post;

$related_posts = get_posts(array(
    'category__in'    => $query_cats,
    'post__not_in'    => $this_post,
    'post_type'       => 'post',

foreach ($related_posts as $post) : setup_postdata($post);

    // Your loop

endforeach; wp_reset_postdata();

This note is tagged:

Adam Walter is a front-end developer, lover of WordPress, and Director of Development at Vital in Portsmouth, NH. Read more about me →