.

< Browse > Home / Wordpress / Blog article: Show Related Posts in Wordpress without any plugins

| Mobile | RSS

Show Related Posts in Wordpress without any plugins

May 28th, 2009 | Comments | Posted in Wordpress

It is always good to avoid as many plugins as you can and instead implement the feature with a code, since too many plugins hamper the loading time of the website and thus leading to a very slow website.

How to implement Related Posts in Wordpress without any plugins?

It is very simple. Just go to your single.php file in Wordpress dashboard. (Dashboard -> Appearance -> Editor -> Single.php) and put this code where you want to display the posts.

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

That is all. Now it will automatically generate all the related posts based on the tags used in the particular post. Do you also have any such methods? Then do let me know of it via comments.

Leave a Reply 3081 views, 2 so far today |

Related Articles:

  • how about adding thumbnails to it
  • hey vikas,

    i have tried this and it doesn't seem to work when you post the related above the comments box... it shows the related properly but it does not show the comments posted ... any ideas?
  • Hey this is very handy and useful Vikas. Specially for people like me who relies more on codes rather then plugin.
  • Rick
    Hey thanks it's nice one but how about showing related post based on category?
  • Thanks Rick for the comment
    Will check it and let you know :)
  • hey, its nice, its better, not to use plugins when we can do the task manually by adding some codes... Going to use it on my blog.
blog comments powered by Disqus