Show Related Post in WordPress Without a Plugin

WordPress Metal Logo

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…

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…

More Resources

About Binny V A 102 Articles
Freelance Web Developer on the LAMP Platform. Maintains a blogs http://blog.binnyva.com/. Other sites include Bin-Co and OpenJS

59 Comments

  1. 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?

  2. 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!

  3. 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.

  4. I need to use both pieces of code together. Can someone explain how to do this?

    Mores said this in comment #15:

    Use category__in with an array of category-IDs and then use tag__and.

    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;
      }
      }

  5. 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

  6. 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 ^^; ).

  7. 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

  8. 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!

  9. 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.

  10. 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.

  11. 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โ€ฆ.

  12. 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.

  13. 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.

  14. 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!

  15. 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

  16. 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.

  17. 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?

  18. 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.

4 Trackbacks / Pingbacks

  1. Weekend Links - Apr 19, 2009 | OMNINOGGIN
  2. Add Related Posts with Images to your WordPress Post Page without a Plugin in php | TechIndia
  3. Posts relacionados por categorias ou tags no WordPress
  4. Add Related Posts, with Images, to your WordPress Post Page without a Plugin · Graphic & Website Design, Website Development & Marketing · New York, NY · pixel8

Leave a Reply to joy Cancel reply

Your email address will not be published.


*