Code #27: Display related posts with a shortcode

This is the twenty sev­enth day of  “31 Days of Cod­ing”, and today we’re going to show you how to dis­play related posts with a short­code. First thing you gotta do is you gotta paste the fol­low­ing code in the fuctions.php file of your theme:

function related_posts_shortcode( $atts ) {
	extract(shortcode_atts(array(
	    'limit' => '5',
	), $atts));

	global $wpdb, $post, $table_prefix;

	if ($post->ID) {
		$retval = '<ul>';
 		// Get tags
		$tags = wp_get_post_tags($post->ID);
		$tagsarray = array();
		foreach ($tags as $tag) {
			$tagsarray[] = $tag->term_id;
		}
		$tagslist = implode(',', $tagsarray);

		// Do the query
		$q = "SELECT p.*, count(tr.object_id) as count
			FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id  = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID
				AND p.post_status = 'publish'
				AND p.post_date_gmt < NOW()
 			GROUP BY tr.object_id
			ORDER BY count DESC, p.post_date_gmt DESC
			LIMIT $limit;";

		$related = $wpdb->get_results($q);
 		if ( $related ) {
			foreach($related as $r) {
				$retval .= '<li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li>';
			}
		} else {
			$retval .= '
	<li>No related posts found</li>';
		}
		$retval .= '</ul>';
		return $retval;
	}
	return;
}
add_shortcode('related_posts', 'related_posts_shortcode');

Next time you make a new post, all you have to do is paste the fol­low­ing short­code wher­ever you would like your related posts to display:

[related_posts]

Stay tuned for tomorrow’s code, which will show you how to inte­grate Adsense on your posts with a shortcode.

4 Comments to “Code #27: Display related posts with a shortcode”

  1. Romario 17 April 2010 at 9:33 pm #

    This is the shit man, thanks a lot dude.

    Like or Dis­like: Thumb up 0 Thumb down 0

  2. Lily 8 May 2010 at 5:50 pm #

    Hi there,

    Does your code above find related posts based on tags? How would you mod­ify it to use cat­e­gories instead?

    Thanks,
    Lily

    Like or Dis­like: Thumb up 1 Thumb down 0

  3. Klajdi 9 May 2010 at 6:22 am #

    Hello Lily!

    I got this code from another site, but I think with the “Yet Another Related Posts Plu­gin” does that!

    Let me know if that works :D

    Like or Dis­like: Thumb up 0 Thumb down 0

  4. Lily 14 May 2010 at 10:44 am #

    Thanks Kla­jdl. I checked out “Yet Another Related Posts Plu­gin” but I don’t think they have a short­code that lets you dis­play the related posts any­where in your post entry…

    Like or Dis­like: Thumb up 0 Thumb down 0


Leave a Reply