How to Add Related Posts Widget to WordPress Without a Plugin

WordPress offers a great platform for you to showcase your content but how do you keep your visitors engaged. Offering high quality content is just one piece of the puzzle, as is an easy-to-navigate structure but after reading your article where does your website visitors go? One great method of keeping your visitors engaged and moving around your website is by including related posts at the bottom of your articles.

You may have noticed the we use a related post widget at the bottom of our articles on VPSBasics. The related post widget includes a selection of automated posts related to the current article you are reading and has been one of the best additions to the website. We have seen advantages for our visitors such as an improved user experience by providing a convenient method for our visitors to find related articles based on their own interests. For us, we have seen lower bounce rates as our visitors have easily found related articles.

In this guide, we will explain how to add a related posts widget to your existing WordPress theme using your functions.php file. If you want to see how the related posts widget will look, just scroll to the bottom of this articles – we use exactly the same code.

How to Add Related Posts Widget to WordPress Without a Plugin

Important

In this tutorial, we'll be directly editing WordPress theme files and we recommend that you create a child theme of your existing parent theme. By using a child theme you will be able to apply modifications without altering the parent theme files and ensuring any changes you make are kept following any parent theme updates.

Note

If you don't feel comfortable with editing the functions.php file directly, we would recommend you use the Code Snippets plugin. This plugin will enable you to easily add, manage and delete WordPress code snippets from your dashboard. To find out more about adding custom code snippets using a plugin see our tutorial How to Add Custom Code Snippets to WordPress with the Code Snippets Plugin for more information.

If you don’t feel comfortable with editing the functions.php file or using the Code Snippets plugin, you can install a free related posts plugin from the WordPress repository. Some of the most popular plugins include Jetpack (5+ million), Contextual Related Posts (70,000+), Inline Related Posts (60,000+), Related Post By PickPlugins (3,000+), WordPress Related Posts Plugin (2,000+).

Firstly, we will need to add the related posts function code in our functions.php file. Just copy and paste the code below:

//Related Posts Widget
function vpsb_related_posts($args = array()) {
    global $post;

    // default args
    $args = wp_parse_args($args, array(
        'post_id' => !empty($post) ? $post->ID : '',
        'taxonomy' => 'category',
        'limit' => 3,
        'post_type' => !empty($post) ? $post->post_type : 'post',
        'orderby' => 'date',
        'order' => 'DESC'
    ));

    // check taxonomy
    if (!taxonomy_exists($args['taxonomy'])) {
        return;
    }

    // post taxonomies
    $taxonomies = wp_get_post_terms($args['post_id'], $args['taxonomy'], array('fields' => 'ids'));

    if (empty($taxonomies)) {
        return;
    }

    // query
    $related_posts = get_posts(array(
        'post__not_in' => (array) $args['post_id'],
        'post_type' => $args['post_type'],
        'tax_query' => array(
            array(
                'taxonomy' => $args['taxonomy'],
                'field' => 'term_id',
                'terms' => $taxonomies
            ),
        ),
        'posts_per_page' => $args['limit'],
        'orderby' => $args['orderby'],
        'order' => $args['order']
    ));

    include( locate_template('related-posts-template.php', false, false) );

    wp_reset_postdata();
}

Now we need to create a new file called related-posts-template.php. This file contains all the different tags we will use to display the related posts widget on our website and provides use with different classes we will use later to add the styling. Just copy and paste the following code into the related-posts-template.php file:

<?php if (!empty($related_posts)) { ?>
    <div class="related-posts">
        <h3 class="related-posts-title"><?php _e('Related Posts', ‘THEME_NAME'); ?></h3>

        <ul class="related-posts-list">
            <?php
            foreach ($related_posts as $post) {
                setup_postdata($post);
            ?>
            <li>
                <a class="title" href="" title="<?php the_title_attribute(); ?>">
                    <?php if (has_post_thumbnail()) { ?>
                    <div class="thumb">
                        <?php echo get_the_post_thumbnail(null, 'medium', array('alt' => the_title_attribute(array('echo' => false)))); ?>
                    </div>
                    <?php } ?>
                    <h4></h4>
                </a>
            </li>
            <?php } ?>
        </ul>
        <div class="clearfix"></div>
    </div>
<?php
}

Important

Don’t forget to replace the THEME_NAME with your own WordPress theme’s textdomain. You can find your theme’s textdomain in the style.css file of your parent theme. It will look very similar to the example below:

/* 
 * Theme Name: Test Theme
 * Theme URI: https://example.com/test-theme
 * Author: Example
 * Author URI: https://example.com/
 * Text Domain: testtheme
 */

Therefore, using the example above we would change the code to <h3 class="related-posts-title"><?php _e('Related articles', 'testtheme'); ?></h3>.

Now we need to add the function we added to the functions.php file earlier to our theme template. Now you will need to copy the single.php file from your parent theme into your child theme. You can use either your favourite FTP program or the file manager from your web hosting control panel.

Once we have made a copy of the single.php file in our child theme simply add the following code where you want your related posts to appear. For example, if you want the related posts to appear after the post navigation but before the comments section you would place the code after the <?php the_post_navigation?> tag but before if ( comments_open() || get_comments_number() ) : tag.

<?php vpsb_related_posts(); ?>

The code above will use the arguments we added earlier in the functions.php file. It will show a maximum of 3 articles based on the existing category and oder them by date published. However, the function we created is very flexible and enables us to adjust some of the arguments to change the numbers of articles displayed, change the orderby criteria or taxonomy.

We have included four examples below which expand on the code above to add more control and flexibility to your related posts widget. If you want to use any of the example just simply swap the <?php vpsb_related_posts(); ?> code in your single.php file.

Display 6 related posts based on the current post tags

<?php 
vpsb_related_posts(array(
   'taxonomy' => 'post_tag',
   'limit' => 6
));
?>

Display 10 related posts based on the current post category and order by the comment count

<?php 
vpsb_related_posts(array(
   'limit' => 10,
   'orderby' => 'comment_count',
   'order' => 'ASC'
));
?>

Display 6 related posts based on a specific post ID and post tags from that post ID

<?php 
vpsb_related_posts(array(
   'limit' => 6,
   'taxonomy' => 'post_tag',
   'post_id' => 115
));
?>

Display 6 related posts based on the current post tags but in a random order

<?php 
vpsb_related_posts(array(
   'taxonomy' => 'post_tag',
   'limit' => 6,
   'orderby' => 'rand'
));
?>

Now we need to add some styling to the related posts widget using our child theme style.css file. The css below will display the related posts 3 wide on desktop and tablet (horizontal). Two wide on tablet (vertical) and one wide when viewed on a mobile. Just copy and paste the css below into your style.css file:

/* RELATED POSTS WIDGET */
.related-posts {
	background:#fff;
	box-shadow:0 1px 4px hsla(20,1%,57%,.1),inset 0 -1px 0 hsla(20,1%,57%,.35),0 0 0 transparent,0 0 0 transparent;
	padding:0px 0 30px 0px;
	margin-bottom:30px;
	border-radius:3px
}
.related-posts-title {
    	margin-bottom: 20px;
   	font-size: 15px;
    	letter-spacing: 0px;
    	font-weight: 700;
    	box-shadow: #2b2c2f 0 -2px 0 inset;
}
.related-posts-list {
	list-style-type:none;
	margin:0;
	padding:0;
	width:100%
}
.related-posts-list li {
	display:inline-block;
	width:33.33333%;
	margin:0;
	float:left;
	padding-right:30px
}
.related-posts-list li h4 {
	font-size:16px;
	color:#353535;
	padding-top: 20px;
}
/* TABLET */
@media only screen and (max-width: 993px) {
	.related-posts-list li {
		display: inline-block;
		width: 50%;
		margin: 0;
		float: left;
		padding-bottom: 30px;
	} 
}
/* MOBILE */
@media only screen and (max-width: 767px) {
	.related-posts-list li {
		display: inline-block;
		width: 100%;
		margin: 0;
		float: left;
	} 
}

Note

The css styling is intended as an example you may have to adjust some of the code to match your own theme.

That’s it. You have now successfully setup a related posts widget in your WordPress theme.

How useful was this guide?

Click on a star to rate it!

Average rating / 5. Vote count:

Be the first to rate this guide.

We are sorry that this guide was not useful for you!

Help us to improve this guide!

Tell us how we can improve this guide?

By VPSBasics

This guide was written by the VPS Basics editorial team, led by Gilberto Van Roosen. They are a unique blend of people, dedicated to providing highly detailed, comprehensive and importantly easy to follow tutorials, written in plain English. They specialise in tutorials for managing Linux servers and its software.

4 Comments for How to Add Related Posts Widget to WordPress Without a Plugin

Join the Conversation

Note: Your email address will not be published when posting a comment.

Note: All comments are held for moderation and are reviewed by our editorial team prior to approval.

VPSBasics uses Akismet anti-spam filters to reduce spam across our website. Our website is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply. Learn how your data is processed.