Home / Display Related Posts by Category
Duplicate Snippet

Embed Snippet on Your Site

Display Related Posts by Category

List 5 posts from the same categories as the current post.

100+
Code Preview
php
<?php
global $post;
if ( ! empty( $post ) ) {
	$categories = get_the_category( $post->ID );
	if ( $categories ) {
		$category_ids = array();
		foreach ( $categories as $category ) {
			$category_ids[] = $category->term_id;
		}
		$query_args = array(
			'category__in'   => $category_ids,
			'post__not_in'   => array( $post->ID ),
			'posts_per_page' => 5
		);
		$related_posts = new WP_Query( $query_args );
		if ( $related_posts->have_posts() ) {
			echo '<div class="related-posts">';
			echo '<h3>Related Posts</h3><ul>';
			while ( $related_posts->have_posts() ) : $related_posts->the_post();
				echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
			endwhile;
			echo '</ul>';
			echo '</div>';
			wp_reset_postdata();
		}
	}
}

Comments

Add a Comment