Add related posts in each posts in WordPress
Introduction
In this article we will learn how we will add related posts to each posts in wordpress according to the tags given. Even though there are so many plugins available to do the same, here I am going to show you a demo of implementing the same without a plugin. I hope you will like it.
Background
Today I was writing some articles in my website, once I finished my writing, I was just thinking about showing the related posts to each posts according to the tags selected. Hereby I will show you how we can implement it.
Before going through it, we can do this in two way.
I will always recommend you to use normal PHP, WordPress implementation which does not require any plugin. Do you know why?
Limitations if use plugins
These all problems will be resolved if you use normal few lines of PHP codes.
If you still need to go for a plugin, you can see some plugins here: Related Posts Plugins
Using the code
Since we need that related posts entry must be seen in each and every posts, we should make some changes in the file called single.php. You can either edit this file or create a widget.
Find out end of each posts, you can inspect one of your page elements in UI and find out the class name and search the same in the single.php file. For me it is class post-excerpt.
Now after that class ends, you need to paste the below lines of codes
[php]
<div class="relatedposts">
<h3>Related posts</h3>
<?php
$orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
‘tag__in’ => $tag_ids,
‘post__not_in’ => array($post->ID),
‘posts_per_page’=>5, // Number of related posts to display.
‘caller_get_posts’=>1
);
$my_query = new wp_query( $args );
while( $my_query->have_posts() ) {
$my_query->the_post();
?>
<div class="relatedthumb">
<a rel="external" href="<? the_permalink()?>"><?php the_post_thumbnail(array(150,100)); ?><br />
<?php the_title(); ?>
</a>
</div>
<? }
}
$post = $orig_post;
wp_reset_query();
?>
</div>
[/php]
You can set your posts count in the below line of code.
[php]
‘posts_per_page’=>5
[/php]
Our next step is to add some css styles to the links.
[css]
<style>
.relatedthumb a {
color: #7a7a7a;
text-decoration: none;
}
.relatedthumb a:hover {
color: #01a821;
}
</style>
[/css]
You can either paste this CSS in single.php file or in style.css
Now update your file, and run your website. Click on any post and see the output.
I have selected a post which is related to JQuery, and got the related posts as follows. It works great.
Please be noted that you need to add tags in each posts, then only this mechanism works.
Reference: Related Posts
Conclusion
That is all. I hope you liked this article. Please share me your feedback.
Kindest Regards
Sibeesh Venu