WordPress Related Posts Without a Plugin


Finding a good “Related Posts” plugin can be hard. Many come with predefined styles or a rigid structure that makes them hard to integrate into your theme. Even worse, most of these plugins are extremely database intensive and some hosts, such as WP Engine, won’t even allow most “Related Post” plugins on their servers (for good reason).

The following code will display related posts by finding posts with the same tags as the current post. Simply add the code to your functions.php file and call it in your template using joints_related_posts();. Note: If you’re using JointsWP, this function is already built in. 
<?php // Related Posts Function, matches posts by tags – call using joints_related_posts(); ) function joints_related_posts() { global $post; $tags = wp_get_post_tags( $post->ID );
if($tags) {
foreach( $tags as $tag ) {
$tag_arr .= $tag->slug . ‘,’;
$args = array(
‘tag’ => $tag_arr,
‘numberposts’ => 3, /* You can change this to show more */
‘post__not_in’ => array($post->ID)
$related_posts = get_posts( $args );
if($related_posts) {
echo ‘
<h4>Related Posts</h4>
echo ‘
<ul id="joints-related-posts">’;
foreach ( $related_posts as $post ) : setup_postdata( $post ); ?>
<li class="related_post">
<a class="entry-unrelated" href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<?php get_template_part( ‘partials/content’, ‘byline’ ); ?>
<?php endforeach; }
echo ‘</ul>
This code is very, very similar to the code found in Bones – however, it has been modified so that if no related posts are found, the “Related Posts” section will not display.