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:
- function getRelatedPost($postID) {
- global $wpdb;
- $tags = wp_get_post_tags($postID);
- $output = ”;
- //gets all of the tag in a particular post
- foreach ($tags as $terms) {
- $first_tag = $terms->term_taxonomy_id;
- $name = $terms->name;
- // mysql query joining wp_post and wp_term_relationships
- $args = “SELECT p.*
- FROM wp_posts p, wp_term_relationships tr
- WHERE p.id = tr.object_id
- AND tr.term_taxonomy_id = $first_tag
- AND EXISTS( SELECT *
- FROM wp_term_taxonomy tt
- WHERE tt.term_taxonomy_id = tr.term_taxonomy_id
- AND tt.taxonomy = ‘post_tag’
- )
- ORDER BY p.post_date DESC LIMIT 0, 5″; // limits 5 post on each tag
- $myposts = $wpdb->get_results($args);
- if ($myposts) {
- foreach($myposts as $post) {
- // to eliminate double post
- if ($postID != $post->ID) {
- $permalink = get_permalink($post->ID);
- $post_title = stripslashes($post->post_title);
- $output .= ”<li><a href=”‘ . $permalink . ‘” rel=”bookmark” title=”[ '. $name . '] ‘ . htmlspecialchars($post_title, ENT_COMPAT) . ‘”>’ . htmlspecialchars($post_title). ‘</a></li>’; // creates a list
- }
- }
- }
- }
- if ($output) {
- //creates html list if there is any result;
- echo ‘<div id=”rellinks” class=”padd”><h5>Related Links:</h5><ul>’;
- echo $output;
- echo ‘</ul></div>’;
- }
- }
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.