Related posts is a very popular feature. My default wordpress installation often includes a plugin that has this functionality. There are quite a few plugins that lets you have this feature…
- Yet Another Related Posts Plugin (YARPP)
- Similar Posts
- Aizattos Related Posts
- WordPress Related Posts
- Wasabi Related entries
The Code
WordPress has been supporting tags in its new released – so the related posts feature can be implemented without the help of any plugins. All we have to do is find the other posts with some same tags as the current post. Just open the single.php
file in your theme and add this bit of code where you want the related posts to show up…
<?php
$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),
'showposts'=>5, // Number of related posts that will be shown.
'caller_get_posts'=>1
);
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo '<h3>Related Posts</h3><ul>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
}
}
?>
This code finds the other post with any one of the tag that the current post has. If you want to show the posts with any one of the categories that the current post has, use this code instead…
<?php
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'showposts'=>5, // Number of related posts that will be shown.
'caller_get_posts'=>1
);
// Rest is the same as the previous code
WordPress Plugin Killer Series
For those who came in late, this post is part of the WordPress Plugin Killer Series. This series will show you how to duplicate the functionality of the a few wordpress plugins without having to install it using custom code in the wordpress theme. The previous posts in this series are…
- Avoid Duplicate Content – Use Canonical URL in WordPress
- Show Popular Posts in WordPress – without a plugin
- Adding Social Bookmarking Button in WordPress – Without Plugins
looks like I have some reading to do. I like the idea, So I had better read the whole killer series.
Thanks
Thanks for this Binny, this will save me a lot of time. Good post.
I implemented the script for catehories but I have a problem. I now get the comments from all the articles (including those recommended).
Here’s an example: http://www.artistick.ro/concepte/deseneaza-in-3d-cu-wacom-vision-1336#more-1336
I found this topic when I was looking for some ways to display related posts.
Could you please tell me how can I display Recent Post on Homepage?
I had trouble with my related posts plugin. This is an easy and effective solution. I don’t have much experience with php etc but I was able to figure out where to put the code and it looks great.
Thanks for sharing this!
if someone has problem with comments using this script
http://www.3mind.at/2009/05/06/code-highlighting/ found the solution.
We have to use in the beggining:
$backup = $post;
and in the end:
$post = $backup;
wp_reset_query();
i hope to help someone
good bye
adeux!
Thank you!!
Since I had the code above the main content area, it was displaying the last post of the related posts, instead of the one the user was viewing.
Thanks for your fix, works perfectly now.
good job, i tested and is working perfectly, thank you
sir, in my theme there is no single.php, what i have to do
thank you! That’s exactly what I was looking for and it worked beautifully!
Great code. Thanks a bunch.
Any ideas how to get category__in and tag__in to co-exist?
Hmm, I think I got it.
Use category__in with an array of category-IDs and then use tag__and.
Hi,
Firstly thanks for sharing.
I practise this code there: http://akdeniz.muverrih.net/ inside slider.php
So i want show related post’s image, bot how?
I used this code today on a project. thanks for posting it up!
@Seyfullah – it should be as simple as adding in the custom field code in where it’s pulling the codes from.
I need to use both pieces of code together. Can someone explain how to do this?
Mores said this in comment #15:
Thanks in advance!
Benjamin, I’m not sure if I can post the code here but here’s what I used to get a list of similar posts for a project I’m working on:
//for use in the loop, list 5 post titles related to first tag on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$first_tag = $tags[0]->term_id;
$args=array(
'tag__and' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>5,
'category__in' => array(26,27,29),
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo "Ähnliche Projekte: ";
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="" class="gray" rel="bookmark" title="Permanent Link to ">,
<?php
endwhile;
}
}
@mores, thanks this is the exact code I’ve been searching the past 4 days for. Only problem is it messes up my comments. Comments for the current post are also added to the last “related” post. Do you have a work around for that?
Can I look at that somewhere?
I suspect you’re using this code in the wrong part of the loop.
Or do I misunderstand and you get the comments for the current AND related post in one?
Still confuse with these line:
‘category__in’ => array(26,27,29),
What am I suppose to fill in for all categories search?
Thanks
Not sure, try removing the entire row.
Thanks Mores!
What if I want to exclude one particular tag?
On my site I use a tag called “feature” to add posts to a rotating feature on the home page, but this tag doesn’t add much to the relatedness of one post to another.
So, I would like to show posts related by all tags excluding feature
Ideas?
JA
JA, use tag__not_in as well. I haven’t tested it, but the WordPress codex features this parameter.
http://codex.wordpress.org/Function_Reference/get_posts
Thanks for this piece of code. It’s definitely what I needed for my website. But can I ask you something? If I use the code that shows the other posts in the same category, is there a way to select only the posts that have for example the “review” tag? Thanks for your answer (and sorry for my poor english ^^; ).
Kenshiro,
Idk if this is what you mean, Maybe a lil more info I can help you better,
from what I got you wanna show a thumb of the post?
Here is the code i use it shows the related post with ratings img and description,
<a href="" title=""><img src="ID, $key, true); ?>" class="thumb" alt="" />
<a href="" title="">post_title) > 25) {
echo substr(the_title($before = '', $after = '', FALSE), 0, 25) . '...'; } else {
the_title(); } ?>
in order for it to work correctly you have to create a thumb folder and include it in your theme check my site for example http://pinkvelvetvids.com/ the main page shows recently added post and random post you can learn all you need to know to create a pages displaying post with tags and more at http://codex.wordpress.org/Template_Tags/query_posts
I was really cursing the one’s who thought of Wp_query() as it can’t getting reset and showing the same query results on one of my theme page. Later i switched to your code for showing related posts and it worked like a charm. Your code is really a life saver. Thanks a lot and keep it up!
Use rewind_posts() to do that.
Thanks for the great bit of script. It was exactly what I was looking for and worked like a charm. It’d be cool if you’d show us how to create a version for the functions.php page that we could call into our pages with a hook as well, that’d be super useful.
Hero … just wrap the code into a function
function relatedposts() {...}
then call the function in your theme files with
Probably works only inside the loop, if you need it outside you’ll need to send along the post ID.
Great post,
it is very useful for my site,
I m using this script for listing all posts, it works perfectly, but I need this list sort by alphabetic order,
Can anybody help me plz….
Ansar, find this line:
'tag__in' => $tag_ids,
and add this line beneath it:
'orderby'=>'title',
This will sort by the first letter of the title.
This is an awesome bit of code and thank you for sharing. I have used it on numerous occasions but one question I have been meaning to ask is this:
If there are no related posts, how can I get something like “There are no related posts at this time” to display.
I have been playing around with it for a while but haven’t gotten it to work. Any ideas or suggestions would be greatly appreciated.
The entire code basically is something like
if ($tags) { do a lot of stuff}
Change that to
if ($tags) { do a lot of stuff} else {echo 'Sorry, no related posts'}
Thanks mores that worked perfectly. And I actually found the correct spot to place it in. I was so close…..lol – I appreciate the help.
No problemo, glad it worked out.
I’ve just added bellow this line:
‘tag__in’ => $tag_ids,
this line (random option):
‘orderby’=>’rand’,
so it displays different thumbnails each time page is refreshed cause I have a twitter backgrounds gallery and don’t care much about the text 🙂
You can see it here how it works:
http://www.twitterevolutions.com/umbrella-in-the-grass-twitter-background/
Thanks a lot!
Hello, i have been use get_the_ID() for the correct functionaly, with Post-ID no work ok.
I pass the code to function, i don’t known with this code seem ok.
Thanks.
Is it possible to prevent WordPress from auto sorting the tags I add in an alphabetical order?
This sorting causes the code above to give priority to the first tags even though they may be less significant than the later ones.
I would the first tag of my post to be the first tag I assign to it, and by that tag to generate those related posts….
thanks!
can you tell me how to make the related post have numeric
exm
related post
1.aaa
2.
3.
4.
5.
please let me know the code
regards
me
You need an ORDERED LIST to do that, not the UNORDERED LIST that’s being used here.
So replace the
and
tags with
and
.
Okay, new attempt to paste in code:
Replace the
and
tags with
and
.
DANG.
Replace UL with OL in the code 🙂
Finally managed to make it. Great code man 🙂 I don`t need a plugin anymore.
most of my posts are in 2 categories so when using code above (for categories) i’m getting duplicate posts. is there any way to avoid it?
thanks
Thanks for the codes. Really useful.
How to show “No Related Posts” when there is no related posts?
First thanks for this great bit of code.
I am a complete noob to wordpress /php so I am sure this is a novice question but… How can I add the thumbnail generated by wordpress 3.0 to this function? Any help would be greatly appreciated.
hello,
You post seems to be very helpful but unfortunately when I cpoy and paste your code on my article for example, and then when I save it – the code is modifying and it doesn’t show the related posts…
What can I do to stop this?
You need to put the code in your template file, not your post.
For some reason when using this code my comments get mixed up between the related posts. How can I fix this?
Thanks
Hey WPFuss – the code in the post is wrong and I’m not sure how it could be left up for so long without someone fixing it..
You need to add a WP Query Reset at the end of the loop for it to work:
THANK YOU!!! I’ve been using another code, but that was interfering with something else I was trying to do. Yours works!!
I also used
‘orderby’ => rand,
in the $args so it’s not just showing the latest posts.
If you are using a Custom Post Type like ‘review’ you can still use this code if you add this argument:
'post_type'=> 'review'
Very helpful. Thank you. 🙂
That’s a pretty good, much faster in loading than a plugin, even you can customize it as per your needs, thx man 😉
hey great code… I was just wondering whether we can display total views post has received using template tags provided by WordPress Popular Posts Plugin http://wordpress.org/extend/plugins/wordpress-popular-posts/
The Popular Posts plugin offers a template tag that you can use like this:
Needs some adapting to work with Binny’s code.
Code was stripped out. Look here:
http://wordpress.org/extend/plugins/wordpress-popular-posts/installation/
all the way at the bottom you’ll find it.
Great piece of code, test it and really works. Amazing work from you man, now I can show related post without plugins…
After following this tutorial, I couldn’t get a couple of things to work. The permalinks will not work with the register_post_type() and arrays outlined in a function; I simply removed this and permalinks worked fine
How can we use these codes to show the posts with similar titles instead of tags and categories? Is there any solution?
Thanks, guy! Now I can easily show random post in all my posts. And most of all, without a plugin. This is a great suff for wordpress. No plugin, no more loading codes.
Thanks a lot, Binny! That solves a major problem for me.
Works !! Thanks for the script ! 😀
and how to make page list without plug in ?
Great piece of code – I incorporated the feature thumb in to add a little visual candy. Was wondering if there is a way to randomize the posts that are “related.”
Thanks,
Dave
Looks like it didn’t like the php code – meant the_post_thumbnail();
Figured it out – add the line
‘orderby’=> rand,
into the $args=array section and it generates a random set of links each time the page is refreshed – very cool!
Dave
I found small bug .
After i used this code on my website, comments was all messed up. When i write comment it take me to another post and comment is written randomly for some other post. If anyone else experience this i try this method
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),
‘showposts’=>5, // Number of related posts that will be shown.
‘caller_get_posts’=>1
);
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo ‘Related Posts’;
while ($my_query->have_posts()) : $my_query->the_post();
?>
<a href="” rel=”bookmark” title=”Permanent Link to “>
<?php
echo '’;
endwhile;
}
wp_reset_query();
}
?>
Hey Aleksandar did u get that solution,
same here i am also getting same problem, conflicting of comments,
if u know the solution plz help me out there
put this in the end of code
before:
echo ”;
}
}
?>
after:
echo ”;
}
wp_reset_query();
}
?>
put your comments code “”
just before “related post” code.
this simple solution worked for me.
Great code. I think that this is one of the best way to show related post wirthout a plugin.
Very helpful. Thanx for
wp_reset_query();
🙂 Great!i’m using using best related post plugin…it more easier no need custom field as thumbnail.
Just upload,active it..viola..its automatically add thumbnail and also you can match it with your theme setting. You can download it from
http://ifile.it/wl26j8x
I used this code and improved with thumbnail images. Thank you for this usefull tutorial
Work perfect in my sites.
Thanks mate
Great – works perfect – thanks!
Thanks for the idea. I also wanted to sort my posts by the number of tags matched. Here’s a solution:
// ...skipped code
function related_order($input) {
return 'COUNT(wp_term_relationships.object_id) DESC, wp_posts.post_date DESC';
}
add_filter('posts_orderby', 'related_order');
$query = new WP_Query($args);
remove_filter('posts_orderby', 'related_order');
// ...skipped code
Of course one may want to add an additional WHERE filter to show posts from the last month only. Or something like that 🙂
Thanks Bin, I just implemented the code at thisismyurl.com and it works great! I had to add global $post to make it work as a widget, but otherwise it’s perfect.
thank you
There is a slight error with this code…
It makes the post show the wrong comments :O
Max
Nice!!!! It works perfect on my website.
Thanks a lot!!
How can we use these codes to show the posts with similar titles instead of tags and categories? Is there any solution?
Thanks for this code. It works just fine, i prefer using codes instead of plugins, much more easier to manage.
Thanks a lot Binny, your code saved me a lot of time 🙂
wohaa! i found what i’m looking for! i’m just remove related tags query and placed related category.. thats cool!
Great work, thanks for this code.
Hi, I always used YARPP, but actually when writing about many topics, no related posts will appear – so this code is simple and useful! Just copy-pasted – and it works perfect. Thanks!
Dude, you forgot about wp-reset-query, you have to use it in your wp loops.
Thanks for this. I did struggle with getting it to work with custom post types for a minute. All you have to do is add ‘post_type’ => ‘your_post_type’ to the args and it worked.
This is great. I don’t like using plugins unless it’s really necessary.
this could be the best if it can also show related posts according to tags and categories.
Thanks you very much. The script works well in my website. Thanks again. 🙂
Hi,
Thanks for sharing..I add the code to my single.php and the it worked, however i find that my post with comments does’t show the comment on post page. Can you help me with this please?
You need to have a code like
in there. If not, open an index.php or single.php from a default-theme and look for this line. It’ll output the comments.
For those who are having problems with the comments, after installing the code, here’s the solution:
Right after the following piece of code:
<?php
}
echo '';
}
}
?>
Add a “wp_reset_query ();”. It will be something like:
<?php
}
echo '';
}
}
wp_reset_query ();
?>
This will solve the problem, at least it worked for me!
Thanks for the help bro!! It works like a charm..I would like to have a title that say related posts at the top how do i achieve that? Thanks for your help in advance.
Is there a way to assign a current-item class to the li element containing the link of the current post? I know that your code does not shows the current post title in the list but it is very easy to change it to do so.
Thank you so much for the code. One of the problems with many existing plugins for this feature is that they use extensive server resources.
‘caller_get_posts’=>1 must be ‘ignore_sticky_posts’=>1. WordPress gives this error otherwise:
Notice: WP_Query was called with an argument that is deprecated since version 3.1! “caller_get_posts” is deprecated. Use “ignore_sticky_posts” instead.
Great piece of code – I incorporated the feature thumb in to add a little visual candy. Was wondering if there is a way to randomize the posts that are “related.”
Thank You!
hello , use this tested wp 3.6.1
in previous post it does not look good
https://www.wuala.com/scriptux/s/related.php/?key=scriptux2
This post will teach you how. I will follow all the steps on my wordpress blog. I have a ‘ Related post’ option from my wordpress theme and i am already . The more engaged your visitors are, the better chance they will convert into a lead or a sale. I want to get your permission to implement those codes into my WP theme project. WordPress plugins cover almost anything you can imagine, from expanding your blog into a CMS, to adding nifty features. Allowing users to navigate throughout your site from topic to topic makes for longer browsing time on the site. The XML dump will include all your posts, with categories and with all its comments. Actually I am not so adroit in coding, but the way you described coding now it is really very easy for me to use your above mentioned. Today, I’ll release my first ever Joomla plugin – the Export to WordPress plugin. Is this because you can display custom post types, post, and pages related. How to Display Related posts with thumbnails in WordPress without any plugin. The following code will display related posts by finding posts with the . We are revealing the very best related posts plugins so you can keep readers longer on your WordPress site. I need this because my hosting provider does not allow the popular related post plugins. You can use a plugin, but you also can use tags and a . WordPress dashboard, without having to log in anywhere else. You can use a plugin, but you also can use tags and a custom code to show related posts. Link all your existing content with only 1 click, get related posts for all your posts today! This post will teach you how to install related posts manually, as well as with a plugin, and explain the benefits of using related posts on your blog. This is how the related posts thumbnails would be shown on your website after. This I know firsthand because I Jetpack Related Posts module on my own blog. Many people use it, but some of them only use them. We are revealing the very best related posts plugins so you can keep. With WordPress plugins, you can do almost everything to add more feature you want, including display related posts in your blog. The upPrev plugin shows a related content box when a visitor nears the . How to display them without a plugin and why are Related Posts important. I don’t know where to add this code? If post haven’t tags, we can use title of post to find related post? After all, creating content like a god won’t mean jack if no one can find. Then you have to add the mentioned code in the end of functions. Please let me know after publishing 7-8 posts. Creating a Mini Plugin to Show Related Posts via Functions. 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. So can you explain more detail? Some of the most popular WordPress plugin categories are based around adding “related posts” to a blog. Displaying related posts is a very great way to help visitors staying longer on your blog. Link all your existing content with only 1 click, get related posts for all your posts today! Why are Related Posts Important for a Website or Blog. Related posts can be easily displayed with plugins, but did you ever wonder how you could display related posts with a Thumbnail without . WordPress Related Posts Without a Plugin. I currently use special post plugin from codecanyon that is awesome.