Skip to content

WordPress: Display Related Posts Under Each Post


In order to display “related posts” under a post,
we can use a script that will find common tags,
and display them as a list after each post.


We will need to edit this file:
“Page Template” page.php

And insert this code:

<!--Related Posts-->
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;

'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'showposts'=>5, // Number of related posts that will be shown.
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo '<h2 class="related_title">Related Posts:</h2><ul>';
while ($my_query->have_posts()) {
<a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php if ( function_exists( 'add_theme_support' ) ) the_post_thumbnail( 'feature-small', array( 'class' => 'index-post-thm alignleft border' ) ); ?></a>
<li class="related_post"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li><div class="line-break"></div>
echo '</ul>';
<!--End Related Posts-->

Before this line:

</div><!--end content-->
Read more from WordPress

Share your thoughts, post a comment.


Note: HTML is allowed. Your email address will never be published.

Subscribe to comments