As you can see at the bottom of the posts on WPExplorer I show links to “Related Posts” which are gathered randomly from the same category as the current post. For today’s WordPress code trick I will show you how to create the loop to get posts from the current category and display a list of random links below your posts so you don’t have to use any plugin.
Related Posts From Category Loop
Simply paste the following loop wherever you want your related posts to appear. Basically the code generates an array of the current post categories and then it queries the database to get other items within these categories. Previously this article showed how to get posts only from the first category, but this method was probably not the best way to display related items. By grabbing posts from all the categories of the current post it will allow your blog to display more unique “related” sections as well as if you don’t have a lot of items in one specific category it will be able to display posts from another related one.
<?php
// Default arguments
$args = array(
'posts_per_page' => 4, // How many items to display
'post__not_in' => array( get_the_ID() ), // Exclude current post
'no_found_rows' => true, // We don't ned pagination so this speeds up the query
);
// Check for current post category and add tax_query to the query arguments
$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;
}
// Query posts
$wpex_query = new wp_query( $args );
// Loop through posts
foreach( $wpex_query->posts as $post ) : setup_postdata( $post ); ?>
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a>
<?php
// End loop
endforeach;
// Reset post data
wp_reset_postdata(); ?>
Display Related Posts Via A Plugin
The guide above shows you how to display related posts via custom code in your theme. However, you can also display related posts via a plugin. There are many great WordPress related posts plugins but one of the most popular ones is the “Yet Another Related Posts Plugin (YARPP)”. This plugin uses advanced code to formulate your related posts and it has various options you can use to customize things, plus there is a Pro version available you can purchase for added features.