Bin-Blog logoBin-Blog

Learn about the latest in Web Development – as soon as I do.

Show Related Post in WordPress Without a Plugin

By • Apr 17th, 2009 • Category: PHP, Scripts, WordPress

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


114 Responses »

  1. Jocuri fete says:

    Great piece of code, test it and really works. Amazing work from you man, now I can show related post without plugins…

  2. redlex says:

    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

  3. Martin says:

    How can we use these codes to show the posts with similar titles instead of tags and categories? Is there any solution?

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

  5. Nadira says:

    Thanks a lot, Binny! That solves a major problem for me.

  6. Girls Secret says:

    Works !! Thanks for the script ! :D

  7. Girls Secret says:

    and how to make page list without plug in ?

  8. Dave says:

    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

  9. Dave says:

    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

  10. Aleksandar says:

    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();
    }
    ?>

  11. Great code. I think that this is one of the best way to show related post wirthout a plugin.

  12. insanoff says:

    Very helpful. Thanx for wp_reset_query(); :) Great!

  13. joy says:

    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

  14. […] and easy way to display related posts without installing a plugin.After a quick search I found this post with the following code: <?php //for use in the loop, list 5 post titles related to first tag on […]

  15. mre says:

    I used this code and improved with thumbnail images. Thank you for this usefull tutorial

  16. helmy says:

    Work perfect in my sites.

    Thanks mate

  17. Jon says:

    Great – works perfect – thanks!

  18. Donatas O. says:

    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 :)

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

  20. menno says:

    thank you

  21. […] but none hit the mark of what I needed. That was until I found this helpful tutorial, entitled Show Related Post in WordPress Without a Plugin by Binny V A. He provides a solution for both tags and categories, which is perfect. (In fact, this […]

  22. There is a slight error with this code…

    It makes the post show the wrong comments :O

    Max

  23. Carlos says:

    Nice!!!! It works perfect on my website.

    Thanks a lot!!

  24. ntaka says:

    How can we use these codes to show the posts with similar titles instead of tags and categories? Is there any solution?

  25. Thanks for this code. It works just fine, i prefer using codes instead of plugins, much more easier to manage.

  26. Vishu says:

    Thanks a lot Binny, your code saved me a lot of time :)

  27. […] Displaying related posts is a very great way to get visitors to stay longer on your blog. You could use a plugin, but to make things even easier you could use this snippet. Source […]

  28. J'Ze says:

    wohaa! i found what i’m looking for! i’m just remove related tags query and placed related category.. thats cool!

  29. Great work, thanks for this code.

  30. Heiko says:

    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!

  31. AntoxaGray says:

    Dude, you forgot about wp-reset-query, you have to use it in your wp loops.

  32. Gary says:

    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.

  33. Frank DeLuca says:

    This is great. I don’t like using plugins unless it’s really necessary.

  34. heradius says:

    this could be the best if it can also show related posts according to tags and categories.

  35. Devendier` says:

    Thanks you very much. The script works well in my website. Thanks again. :)

  36. Rick says:

    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?

    • mores says:

      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.

  37. Igor Sousa says:

    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!

    • Rick says:

      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.

  38. Alfonso says:

    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.

  39. Mahesh says:

    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.

  40. maarten says:

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

  41. krishna says:

    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!

  42. SCRIPTUX says:

    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

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>