WordPress Related Posts without Plugins

Published on Monday, May 23, 2011
php

Add Related Posts section in your article is nice for your article reader.

The easy way is to find a plugin to install. and set a little bit to get it.

Here we have another solution, maybe you do not want to install too much plugins in your blog. So you have to change code by yourself.

Open WordPress theme’s single post template. In proper location which you think is good , to paste the following code (you might have to change some code due to your theme and requirement):

<!-- my code start -->
<br />
<div>
<br />
<span class="postcomment">
<?php
//list 5 post titles related to first tag on current post
<span class="attr">tags</span> = <span class="attr">wp_get_post_tags</span>(post->ID);
if ($tags) {
?>
<h3><?php _e('Related Posts', 'f2') ?> </h3>
<?php
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>5,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<h4><a href="&lt;?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<?php the_title(); ?></a></h4>
<?php
endwhile;
}
}
?></span>
</div>
<!-- my code end -->