Hey, You found me.

Welcome to my site. I am a filipino web designer who's been creating web designs for 10 years. This is where I usually stash my selected art works, projects, and random thoughts.

More
Codes
6Feb2010

Howto: Add Related Topics without a plug-in

I have been busy trying to create a new layout for my website and I want to incorporate related topics without having to rely on a plug-in. I found this tip on how to add related topics using tags.  I have encountered a lot of problems when using query_post() or new WP_Query() inside the loop. It seems that the the_ID somehow always screws up. Also, from that code, it only searches for posts from the first tag and only works in single pages. I wanted to show posts from all of the tags added in my post.

My solution was to create a function and get all the post related to each of the tags; limiting them to 5 post per tag.

Add this inside the function.php in your theme:

  1. function getRelatedPost($postID) {
  2. global $wpdb;
  3. $tags = wp_get_post_tags($postID);
  4. $output = ”;
  5. //gets all of the tag in a particular post
  6. foreach ($tags as $terms) {
  7. $first_tag = $terms->term_taxonomy_id;
  8. $name = $terms->name;
  9. // mysql query joining wp_post and wp_term_relationships
  10. $args = “SELECT p.*
  11. FROM wp_posts p, wp_term_relationships tr
  12. WHERE p.id = tr.object_id
  13. AND tr.term_taxonomy_id = $first_tag
  14. AND EXISTS( SELECT *
  15. FROM wp_term_taxonomy tt
  16. WHERE tt.term_taxonomy_id = tr.term_taxonomy_id
  17. AND tt.taxonomy = ‘post_tag’
  18. )
  19. ORDER BY p.post_date DESC LIMIT 0, 5″; // limits 5 post on each tag
  20. $myposts = $wpdb->get_results($args);
  21. if ($myposts) {
  22. foreach($myposts as $post) {
  23. // to eliminate double post
  24. if ($postID != $post->ID) {
  25. $permalink = get_permalink($post->ID);
  26. $post_title = stripslashes($post->post_title);
  27. $output .= ”<li><a href=”‘ . $permalink . ‘” rel=”bookmark” title=”[ '. $name . '] ‘ . htmlspecialchars($post_title, ENT_COMPAT) . ‘”>’ . htmlspecialchars($post_title). ‘</a></li>’; // creates a list
  28. }
  29. }
  30. }
  31. }
  32. if ($output) {
  33. //creates html list if there is any result;
  34. echo ‘<div id=”rellinks” class=”padd”><h5>Related Links:</h5><ul>’;
  35. echo $output;
  36. echo ‘</ul></div>’;
  37. }
  38. }

Now that you’ve added this function, use this code anywhere inside or outside the loop:

<?php getRelatedPost($post->ID);  ?>

You can also customize the CSS using the #related-links.

I already incorporated this function on my current theme. To see a working example just look bellow. It gets a little messy if you have a lot of tags. Also, this code isn’t perfect; if you have any suggestions, please feel free to comment.

Anyway, enjoy.


Comments


blog comments powered by Disqus


Popular Posts