Display Related Posts in WordPress Without a Plugin


Posted in Web Development on October 18, 2017

In this guide I'll show you how to display related posts below your content in Wordpress. Together we will cover multiple approaches as well as how to display related custom post types.

Related post functionality is an often desired feature for WordPress website owners. The small grid of related articles below a blog post has become widely used. It is so commonplace and effective that many online advertising platforms have modeled the display for their ad units.

The high demand for this feature has spawned an entire category of WordPress plugins to handle the job. While there are advanced related posts plugins that intelligently handle the serving of related content, they are often overkill.

Running out to find a plugin to handle every little job in WordPress is a slippery slope. In this article I will show you how to create robust related posts functionality without the need for a plugin. For the average blogger or website owner, this functionality will be more than enough!

Why Avoid a Plugin For Related Posts?

The WordPress community is absolutely massive. As of September 2017, CodeinWP reported that roughly 28% of websites are using WordPress. This popularity means that 3rd party plugins, themes, and support for the CMS is widespread.

With this popularity you'll find a wide range of plugins that are fantastic. Over my many years as a WordPress user I have found a great set of plugins that I swear by. To find these options, I had to try many poor options.

Turning to a plugin for every feature or tweak in WordPress is a slippery slope. Poor plugins use can bring compatibility issues, slow site performance, and expose your site to security vulnerabilities. Even if you only use fantastic plugins, it's easy to go overboard. As a WP admin, I urge you to follow the 'less is more' rule.

Related post functionality is one place where I recommend you DON'T use a plugin. It is straightforward to hard-code a nice related post system.

Create the Basic Related Posts Functionality

Before we jump into the code, I want to cover the basic concepts. Our related post system will be constructed of a query and a loop.

  • The query will select WordPress posts from the MySQL database based on our instructions.
  • The loop will output the post information on the page. In our case this will be things like the post thumbnail, title, date, and author.

The code that handles both of these parts will be placed in our theme's single.php template file to be displayed below our blog posts.

Getting the Related Posts with WP_Query

The first step in this process is to write some custom arguments that will drive our WP_Query. This is where the logic of the related posts happens. The first example I'll give here is the most basic scenario you'll run into. I'll dive into some more custom examples later that will let you tweak the output.

This basic example creates a custom query written in PHP that grabs 8 random related posts from the default WordPress 'post' post type. It also ensures that the current post is not in the results. It then initiates WP_Query using the custom arguments provided.

// Build our basic custom query arguments
$custom_query_args = array( 
	'posts_per_page' => 8, // Number of related posts to display
	'post__not_in' => array($post->ID), // Ensure that the current post is not displayed
	'orderby' => 'rand', // Randomize the results
);
// Initiate the custom query
$custom_query = new WP_Query( $custom_query_args );

You can modify the number of posts returned and the order based on your preference.

Styling the Output with The Loop

Next, we need to loop through the resulting posts and output some data for each one. This is a straightforward bit of code. You'll see we are also grabbing the medium post thumbnail (featured image) if there is one available.

// Run the loop and output data for the results
if ( $custom_query->have_posts() ) : ?>
	<?php while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
		<?php if ( has_post_thumbnail() ) { ?> 
			<a href="<?php the_permalink(); ?>"> <?php the_post_thumbnail( 'medium' ); ?></a>
		<?php } ?>
		<a href="<?php the_permalink(); ?>"><b><?php the_title(); ?></b></a>
	<?php endwhile; ?>
<?php else : ?>
		<p>Sorry, no related articles to display.</p>
<?php endif;
// Reset postdata
wp_reset_postdata();

After the loop, we run a reset on the query using wp_reset_postdata which would enable us to run another WP_Query later on the same page if we choose.

Putting it All Together

The final code is simply one part after the other. Insert it into the template file of your theme or child theme where you'd like the related posts to display.

<!--Start Related Posts-->
<?php
// Build our basic custom query arguments
$custom_query_args = array( 
	'posts_per_page' => 8, // Number of related posts to display
	'post__not_in' => array($post->ID), // Ensure that the current post is not displayed
	'orderby' => 'rand', // Randomize the results
);
// Initiate the custom query
$custom_query = new WP_Query( $custom_query_args );

// Run the loop and output data for the results
if ( $custom_query->have_posts() ) : ?>
	<?php while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
		<?php if ( has_post_thumbnail() ) { ?> 
			<a href="<?php the_permalink(); ?>"> <?php the_post_thumbnail( 'medium' ); ?></a>
		<?php } ?>
		<a href="<?php the_permalink(); ?>"><b><?php the_title(); ?></b></a>
	<?php endwhile; ?>
<?php else : ?>
		<p>Sorry, no related articles to display.</p>
<?php endif;
// Reset postdata
wp_reset_postdata();
?>
<!--End Related Posts-->

Expanding to More Advanced Use Cases

The above code is going to work well for your basic related posts display. For a small site with a similar post theme, it might do the trick for some time to come. For a larger site with more types of content or categories, it would be nice to be more selective on the returned posts.

I've put together a few additional examples below to show you how to set the args for the WP_Query to select posts by related categories, related tags, and custom post types.

Related Posts by Category

If you use categories to organize your posts, its likely that you'd want to display posts from the same category for your user. Use the following to build your WP_Query to do just that:

// Get a list of the current post's categories
$catidlist = '';
foreach( $categories as $category) {
    $catidlist .= $category->cat_ID . ",";
}
// Build our category based custom query arguments
$custom_query_args = array( 
	'posts_per_page' => 8, // Number of related posts to display
	'post__not_in' => array($post->ID), // Ensure that the current post is not displayed
	'orderby' => 'rand', // Randomize the results
	'cat' => $catidlist, // Select posts in the same categories as the current post
);
// Initiate the custom query
$custom_query = new WP_Query( $custom_query_args );

Related Posts by Tags

This display is the most robust of all the examples here. The code gets the current tags for a post. It then selects related posts that have related tags. It also has a fallback to pull from all posts if no related tags are found.

This is a great way to hand control which related posts display, and to show related posts across categories.

// Get the tags for the current post
$orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
// If the post has tags, run the related post tag query
if ($tags) {
	$tag_ids = array();
	foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
// Build our tag related custom query arguments
$custom_query_args=array(
	'tag__in' => $tag_ids, // Select posts with related tags
	'posts_per_page' => 8, // Number of related posts to display
	'post__not_in' => array($post->ID), // Ensure that the current post is not displayed
	'orderby' => 'rand', // Randomize the results
);
} else {
// If the post does not have tags, run the standard related posts query
$custom_query_args = array( 
	'posts_per_page' => 8, // Number of related posts to display
	'post__not_in' => array($post->ID), // Ensure that the current post is not displayed
	'orderby' => 'rand', // Randomize the results
);
}
// Initiate the custom query
$custom_query = new WP_Query( $custom_query_args );

Custom Post Type Related Posts

If you want to display related posts in a custom post type you've created, you can use the following code to get the job done. Simply change custom-post-type to the slug of the post type you would like to display.

// Build our custom post type custom query arguments
$custom_query_args = array( 
	'post_type' => 'custom-post-type', // Select entries from a custom post type, input your slug here
	'posts_per_page' => 8, // Number of related posts to display
	'post__not_in' => array($post->ID), // Ensure that the current post is not displayed
	'orderby' => 'rand', // Randomize the results
);
// Initiate the custom query
$custom_query = new WP_Query( $custom_query_args );

Wrapping it Up

Between the WP_Query and The Loop, you can put together a powerful related post display for your website. If you have any questions, be sure to comment below.


Share:

Subscribe for the latest posts delivered directly to your inbox.

Don't miss an update!

Related Posts


Leave a Reply

Your email address will not be published. Required fields are marked *