Related Posts in WordPress Without Plugin

Related Posts in WordPress Without Plugin

In this article we’ll discuss about related posts in WordPress. How to display them without a plugin and why are Related Posts important. Many people use it, but some of them only use them because others do as well. They don’t know the reason of it, why it helps and other small important things.

Related Posts

Why are Related Posts Important for a Website or Blog

Related Posts as you might expect, display related contact to the specific article you are viewing. And by using related posts to display similar content, the visitors of your website might be interested in another article that has been displayed there. This means they stay more on your website, which reduces the bounce rate. (You may use Google Analytics to check bounce rate).

How to Add Related Posts in WordPress Without Plugin

To be able to add this functionality to your WordPress website, you’ll need to have a bit coding skill. We provide you a walk through about how to do it step by step. But you need to know how to access your themes files. (Default path is: www.example.com/wp-contant/themes/mytheme).

After you’ve found your themes folder, search for functions.php and create a backup of it. Then open it up. This is the file which contains every custom functions used by your theme. The first thing we need to do is to create our function. So scroll down to the bottom of the file and add the following:

function my_related_posts() {
}

This will be your function that will display the related content to each of your posts when someone views it. After this we need to add some arguments. Arguments are used to let the function know what we want to be similar in the related articles and in the current one. To do this, we add a variable called $args. (Function Reference/wp parse args) In this variable we store two things. Firstly how many posts we want to display and secondly what are the conditions for the articles to be display. Add the following inside your function:

$args = array(
        'posts_per_page' => 5,
        'post_in'  => get_the_tag_list()
);

The next step is to create another variable, called $the_query. (Class Reference/WP Query) This variable is used by WordPress to it display the posts. Used the following code to add our arguments to it:

$the_query = new WP_Query( $args );

Now what we need to do is actually display the posts. To do this we use a while loop which looks like the following:

echo '<ul>';
while ( $the_query->have_posts() ) : $the_query->the_post();
        ?> 
        <li><a href="<?php the_permalink(); ?>">< ?php the_title(); ?></a> </li>
        < ?php
endwhile;
echo '</ul>';

The code above will display each related post as an anchor tag (link). The fine step is to reset the query. Add the following piece of code to do this:

wp_reset_postdata();

Your final code should look like the following:

function my_related_posts() {
$args = array(
        'posts_per_page' => 5,
        'post_in'  => the_tags()
    );
echo '</ul><ul>';
while ( $the_query->have_posts() ) : $the_query->the_post();
        ?> 
        <li><a href="<?php the_permalink(); ?>">< ?php the_title(); ?></a> </li>
        < ?php
endwhile;
echo '</ul>';
 wp_reset_postdata();
}

Use the following code to display the posts where you want:

my_related_posts()

If you’re using Genesis Framework used the following snippet:

add_action('genesis_after_content','my_related_posts');

Adding Some Style to the List

The code above will just display a simple list. But that doesn’t look too nice right? So why don’t we add some style to it. Like a small thumbnail or the data when the post was written, or in which category it belongs to. Well, to do this we need to add some extra code into our code.

To display Related Posts before the list, add the following code before the echo ‘<ul>';

echo '<h2>Related Posts</h2>';

If you want to add thumbnails to it, add the following code before code below:

<a href="<?php the_permalink(); ?>">< ?php the_title(); ?></a>

The code:

< ?php if ( has_post_thumbnail() ) { ?>
<div class="related_thumb"><a href="<?php the_permalink(); ?>">< ?php the_post_thumbnail(); ?></a></div>
< ?php } ?>

So your code will look like this:

while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<li>
< ?php if ( has_post_thumbnail() ) { ?> 
<div class="related_thumb"><a href="<?php the_permalink(); ?>">< ?php the_post_thumbnail(); ?></a></div> 
< ?php } ?>
<a href="<?php the_permalink(); ?>">< ?php the_title(); ?></a>
</li>
< ?php
endwhile;

Stylish Display

If you want to display the post as thumbnails with the title below it near each other, like on the image, use the codes below:

Related Posts Thumb

The Function Code:

function ll_related_posts() { 
$args = array(
'posts_per_page' => 5,
'post_in'  => get_the_tag_list(),
); 
$the_query = new WP_Query( $args ); 
echo '<section id="related_posts">'; 
echo '<h2>Related Posts</h2>'; 
while ( $the_query->have_posts() ) : $the_query->the_post();
?> 
</section><section class="item">
< ?php if ( has_post_thumbnail() ) { ?> 
</section><section class="related_thumb"><a href="<?php the_permalink(); ?>">< ?php the_post_thumbnail( 'related-post' ); ?></a></section> 
< ?php } else { ?>
<section class="related_thumb"><a href="<?php the_permalink(); ?>"><img src="<?php bloginfo('template_directory')?/>/lib/images/thumb.png" /></a></section>
< ?php } ?> 
< ?php the_title(); ?>

< ?php
endwhile; 
echo '<div class="clear">'; 
wp_reset_postdata(); 
}

The CSS

#related_posts {
	margin-top: -10px;
	margin-bottom: 10px;
	padding-bottom: 20px;
	border-bottom: 20px solid #E2E2E2;
}

#related_posts .item {
	width: 132px;
	max-height: 200px;
	overflow: hidden;
	float: left;
	margin: 6px;
	font-weight:bold;
	text-align:center;
}

#related_posts .item img {
	-webkit-box-shadow: 0 0 4px #999;
	box-shadow: 0 0 4px #999;
	border: white solid 1px;
	padding: 4px;
	margin: 0 auto;
	background: #f2f2f2;
}

Conclusion

In this article we learned how to display related posts in WordPress without a plugin and why is it important. Also now we know how to stylize them to be displayed. So, why to use a plugin to display related posts when we can do it without a plugin? If you have any questions, feel free to ask them in the comment section below.

Comments

  1. says

    Great post, Andor. I didn’t know that it is possible to have reklated posts with thumbnails, which look mich more pleasant for the eyes. Also, we shouldn’t forget about the SEO function of the related posts as they create wonderful interlinking network within your site.
    Marcel Fischer recently posted – Best Sports and Fitness Android AppsMy Profile

  2. Veronica says

    When a reader finds an article very interesting, he will look at the related articles for further reading. People who want more information rely on this. Thanks for posting.

  3. says

    Big thanks for this code snippets – I search along time for such a solution without activating for every new feature a special plugin which will cost a lot of ram…

  4. Kristine says

    Everytime I get interested in an article, I often see the related posts so that I ca find more about it. I’m keen on knowing a lot more stuff that’s why I do it. Related posts are definitely a must.

  5. says

    I use nrelate as well, but I’m curious as to why you would spend time building your own. Would there be any advantage over the plugin? Personally, I try to use as little plugins as possible and relaying on 3rd to pull data for you. What it they start to charge for the service, or what if their server goes down? I prefer to keep as much development of features in house as much as possible. nrelate works well for me. But I’m will to give this a try.

  6. Joe Hart says

    Hi Andor..Really helpful tutorial…I manage a few WordPress sites and Blogger sites…Do you know any hack to get this similar feature in Blogger…Most ‘Related Posts’ widget do not work with blogger…They also do not have any extensions for the same.
    Joe Hart recently posted – Dental ImplantsMy Profile

  7. says

    Decided to delete the Related post WP plugin and then searching more than 20 blog about show related post without plugin, but none has succeeded I apply on my blog include this one. Can you teach me more specific where to put all the code that shown above.
    Thank you

  8. Asif Mushtaq says

    Thanks for nice sharing can you tell me how to add in PHP..? mean i Have added the function in functions.php and how to add php code in single.php..?

    • says

      Hello,

      If you added the code to your functions.php, you just need to add the following code to your single.php to display the related posts:

      if ( function_exists( ll_related_posts() ) ) {
      		ll_related_posts();
      	}
      

      Remember, “ll_related_posts” s your function’s name, this might be different for you depending on what name you gave to your function.

      Best regards,
      Andor Nagy

  9. says

    Recently I have released a Related Posts plugin, which is an extension to the Meta Box plugin by Rilwis. My plugin puts the user (back) into the driver’s seat by giving control on what should be a related post.

    The plugin (SO Related Posts – link to WP Repo via my name) adds a Custom Meta Box right under the Post with a drop down menu to choose from all the published Posts. The user can add as many Posts as needed or none at all, it doesn’t matter.

    On the front end the output has its own class and an unordered list, which automatically is added after the_content().

    With this plugin I would like to offer an alternative to the other Related Posts plugins.
    Piet recently posted – SO Related PostsMy Profile

  10. Tienho says

    Hello.

    thanks for you sharing. I used the code, but it not works, i had check the code with editer code “sublime text” and i look the code is wrrong, so can you send me sample file single.php and function.php ?

    Thanks .

 Comment Policy

Your words are your own, so be nice and helpful if you can. Please, only use your REAL NAME, not your business name or keywords. Using business name or keywords instead of your real name will lead to the comment being deleted. Anonymous commenting is not allowed either. Limit the amount of links submitted in your comment. We accept clean XHTML in comments, but don't overdo it please. You can wrap code in [lang-name][/lang-name] tags.


Tell us what you're thinking...

If you want a picture to show with your comment, then get Gravatar!

CommentLuv badge