$tags = wp_get_post_tags( get_the_ID(), [ 'fields' => 'ids' ] );

$related = new WP_Query( [
	'tag__in'             => $tags,
	'post__not_in'        => [ get_the_ID() ],
	'posts_per_page'      => 2,
	'ignore_sticky_posts' => true,
	'orderby'             => 'rand',
	'no_found_rows'       => true,
] );

<?php if ( $related->have_posts() ) : ?>

	<section class="related-posts-wrapper">
		<h2><?php esc_html_e( 'Related Posts', 'dorzki' ); ?></h2>

		<ul class="related-posts">

			<?php while ( $related->have_posts() ) : $related->the_post(); ?>

				<li class="post-wrapper">
					<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

			<?php endwhile; ?>


<?php endif; wp_reset_postdata(); ?>

Credit: dorzki.co.il

How to use it?

Usually adding functionality to a WordPress site is by creating a plugin.
However you can simply copy the code and paste it in your child theme’s functions.php file at the end of the file, just before ?>.

For JavaScript code you will need to add them to your theme’s main JavaScript file.

Having issues with the code?

If the code doesn’t work or you get an error please let us know in the comments section.
We will do our best to fix it as-soon-as-possible and update the code on this page.


  1. Vladartis

    I would also add

    'no_found_rows' => true

    to loop arguments. It will remove the support of pagination and save one DB query.

    1. Dor Zuberi

      Hi Vladartis,
      Thanks for that, I’ve updated the snippet.

Leave a Reply