How To: Related Posts in WordPress Feeds

Published 14th December 2009

In this tutorial I’m going to show you how to add a list of related posts by tag to your feeds in WordPress. And yes we are going to do it the good old fashioned way by coding it ourselves. The function for getting related posts can be used to show them on normal posts as well but for this example we add some extra bit’s to make sure they only show up in our feed and not on our normal posts. It’s also worth mentioning that this code will add the related posts list to all of your feeds (e.g. RSS, RSS2, Atom etc) as WordPress generates multiple types of feed for your blog automatically.

The Code

So for you copy and paster’s out there here is the code. This goes into your functions.php file.

function feed_related_posts($content) { global $post; $showposts = 5; if(is_feed()){ $tags = wp_get_post_tags($post->ID); if($tags) { $first_tag = $tags[0]->term_id; $args=array( 'tag__in' => array($first_tag), 'post__not_in' => array($post->ID), 'showposts'=>$showposts, 'caller_get_posts'=>1 ); $my_query = new WP_Query($args); if($my_query->have_posts()) { $content .= '<h3>Related Posts</h3>'; $content .= '<ul>'; while ($my_query->have_posts()) { $my_query->the_post(); $content .= '<li><a href="'. get_permalink() .'" title="Permanent Link to '. the_title_attribute('echo=0') .'">'. get_the_title() .'</a></li>'; } $content .= '</ul>'; } } } return $content; } add_filter('the_content','feed_related_posts');

So what’s going on here? Well there are several things you should notice:

  • The most important thing to notice is we are using the “the_content” filter. This let’s us manipulate content before it’s printed on the screen (in this case we are adding a list to the bottom of the post). This is also why the function takes a $content parameter and must return $content.
  • The next important thing to notice is the is_feed() function we use. This makes sure we are only printing out the content on our feeds rather than the visible post.
  • The rest is just the normal way of getting related posts. We get the post tags, then we create an array of arguments that get pumped into a WP_Query which get all other posts with the same first tag, then output the result as a list of post titles. Simple.

Conclusion

So there you have it. A simple way of adding a list of related posts to your feeds in WordPress. As always let me know if you find any bugs or if you think this code could be improved.