Blog

Wordpress - Related Posts Script

At my job, I currently have three Wordpress sites under my watchful eye. On one, I was tasked with creating a related posts feature. Now, there are certainly enough plug-ins that will do just that, but none of them worked how I wanted to or were generally more complex than necessary. So, I whipped up this little script:

Code: php
  1. function relatedPosts($id) {
  2. /* Build a query to get a list of all posts that share similar tags */
  3. $s = microtime(true);
  4. $q = "SELECT count(*) AS total, p.ID, p.post_title, p.post_date FROM wp_posts p INNER JOIN wp_term_relationships t ON p.ID=t.object_id AND t.term_taxonomy_id in (SELECT s.term_taxonomy_id FROM wp_term_relationships s WHERE s.object_id=$id) AND t.object_id != $id AND p.post_status='publish' GROUP BY p.id ORDER BY total DESC, p.post_date DESC LIMIT 5";
  5. /* Format the output */
  6. $out = "";
  7. $result = @mysql_query($q);
  8. if ($result && @mysql_num_rows($result) > 0) {
  9. $out = "<h3 class=\"related\">Related Posts</h3><ul class=\"related\">";
  10. while ($row = mysql_fetch_object($result)) {
  11. $perma = get_permalink($row->ID);
  12. $out .= '<li><a href="'.$perma.'">'.$row->post_title.'</a> - '.date("F j, Y", strtotime($row->post_date)).'</li>';
  13. }
  14. $out .= "</ul>";
  15. }
  16. echo($out);
  17. }
  18. ?>

Just drop that in the wp-content/yourtheme/functions.php file, where yourtheme is the directory of your active theme. Then add the following in your wp-content/yourtheme/single.php where you want the related posts to appear:

Code: php
  1. relatedPosts(get_the_ID());
  2. ?>

You should now have a list of posts with similar tags. Styling is simple: one h3 and one ul, both with the class "related".

Enjoy!