WordPress loop hack: Show related posts with full HTML and CSS control

Posted June 22, 2009 by Brian Cray

Reading time: About 0 minutes

Use this code on single.php inside “the loop” to show related posts based on the current post’s tags. Customize the HTML and CSS as you see fit. Enjoy!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<h2 id="related">Related Posts</h2>
<?php  
$rel_tags = get_the_tags();
foreach($rel_tags as $rel_tag)
{
	$rel_tagnames .= $rel_tag->name . ',';
}
$rel_posts = get_posts('tag=' . $rel_tagnames . '&post__not_in' . $post->ID . '&showposts=5');
if (count($rel_posts)) : ?>
	<ul>
	<?php foreach((array) $rel_posts as $rel_post) { ?>
		<li><a href="<?php echo $rel_post->post_name ?>"><?php echo $rel_post->post_title ?></a></li>  
	<?php } ?>
	</ul>
<?php else : ?>
	<p>I can't find any related posts, sorry!</p>
<?php endif; ?>

About the author

Photo of Brian Cray

Brian Cray is a Columbus, Ohio-based web entrepreneur & consultant. View some of Brian’s work in his portfolio and learn how to make kick ass websites by reading his blog.

4 Article comments

Show/add comments

0 Article references from other blogs

Show all references

768
Previous:
Next: