Lazy Related Posts WordPress Query

Sometimes you just need to output some posts based on the post you are already on. You could place this code on your single post template and it would return 3 posts based on the categories said post are associated with. The 'post__not_in' => array(get_the_ID()), line ensures the post you are currently on doesn’t show in this list.

<?php
$related_query = new WP_Query(array(
	'post_type' => 'post',
	'category__in' => wp_get_post_categories(get_the_ID()),
	'post__not_in' => array(get_the_ID()),
	'posts_per_page' => 3,
	'orderby' => 'date',
));
?>
<?php if ($related_query->have_posts()): ?>
	<ul>
		<?php while ($related_query->have_posts()): ?>
			<?php $related_query->the_post(); ?>
			<li>
				<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
			</li>
		<?php endwhile; ?>
	</ul>
	<?php wp_reset_postdata(); ?>
<?php endif; ?>

I am hoping in the near future this is something that can be achieved with the Full Site Editor and the Query block.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.