If you’re building a WordPress website, you may come across a scenario where you need to display related posts based on the current post’s category. This is a common requirement for blog posts and other content-rich websites.
The good news is that you can easily achieve this using WordPress’s built-in “WP_Query” class. This class allows you to query the WordPress database for posts that match certain criteria, such as category, tag, author, date, and more.
The code snippet below demonstrates how to use WP_Query to display related posts based on the current post’s category:
<?php
$related_query = new WP_Query( array(
'post_type' => get_post_type(),
'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() ) : $related_query->the_post(); ?>
<li>
<a href='<?php the_permalink(); ?>'><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php wp_reset_postdata(); ?>
<?php endif; ?>https://gist.github.com/philhoyt/f54c1bb45fe843fd38bda0ed131b1cc3
Leave a Reply