CodeHQ

Query posts by current post category

Great for showing ‘related posts’ by current post category. The current post has an ID, the query grabs that ID, checks with categories are associated with that post, creates an array and passes these through to the query, also excluding this current post from the loop.

Output is posts from the same category/categories as the current post (active page).

<?php 
	$args = array(
		'posts_per_page' => 3,
		'post__not_in'   => array( get_the_ID() ),
		'no_found_rows'  => true, //Np pagination needed so query is quicker
		'post__not_in' 	 => array($post->ID)  //Excludes current post
	);
 
	$cats = wp_get_post_terms( get_the_ID(), 'category' ); 
	$cats_ids = array();  
	foreach( $cats as $wpex_related_cat ) {
		$cats_ids[] = $wpex_related_cat->term_id; 
	}
	if ( ! empty( $cats_ids ) ) {
		$args['category__in'] = $cats_ids;
	}
	$wpex_query = new wp_query( $args );
 
	foreach( $wpex_query->posts as $post ) : setup_postdata( $post ); ?>
 
	//CONTENT HERE i.e. post data and title
 
<?php endforeach; wp_reset_postdata();?>