Post Pic

WordPress shortcode to display related posts

Last week, I shown you how to display your related posts without using a plugin. But what about using a WordPress shortcode, which will allow you to define where the related posts might be displayed?

To create the shortcode, simply open your functions.php file and paste the shortcode function:

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');

Once done, you can use the following shortcode in your posts to display the related content:

[related_posts]

Thanks to Blue Anvil for this awesome shortcode!

4 Responses

Dec 25 2011 03:42

Thanks. Great post. Just what I was looking for.

Do you know if this use of the Shortcode will be as performant as using the related posts in Simple Tags?

Jun 11 2012 08:06

I find you method of displaying related posts very convenient especially with the shortcode and an option to show the limit of related posts to show. Thanks for the tip, saved me a lot of time :D

Jun 16 2012 01:39

What if i want something like this?

[Some title here]
1. Related post
2. Related post
3. Related post
4. Related post
5. Related post
[Some text here]

I’m new to WordPress. Thanks.

Sep 01 2012 12:22

Can I call this function from single.php?. I want to put related post to my footer post (below social bookmark).

Thanks, sorry for my english,

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox