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!

23 Responses

Mar 30 2009 15:05

How to display SHORTCODE on SINGLE POST only? and when on Home page the shortcode will not displayed anything

Mar 30 2009 21:18

Great shortcode, I’m using it at http://www.ilovecolors.com.ar/ilc-thickbox-wordpress-plugin-to-display-images/
I’ve added a bit of markup and text to the $retval variable.
I like the fact that it is a shortcode so I’m free to apply it whenever I want. However, when I get sometime off I will create a meta checkbox for the sidebar in order to enable/disable related posts for a particular post instead of writing the shortcode.
Jauhari, maybe you could use is_single, to check if you’re in a single post page.

Mar 31 2009 04:49

Jauhari, I think you can use if (is_single) {//shortcode here}.

Mar 31 2009 06:39

The shortcode have to be pasted in single posts, in the editor in source mode. Not in templates!

Apr 01 2009 21:21

Thanks for sharing. There are always situations when we want to share related posts to our visitors, and the way to do it automatically and with shortcode is very useful.

Apr 02 2009 00:04

I’ve been using a plugin to do this, but I might have to implement this in my next theme now that I know how to. THanks.

Apr 02 2009 17:05

Hi Selinap..
Is that you mean, put this code

if (is_single) {//shortcode here}.

On the post? Did it work?

Apr 02 2009 17:09

@Jean-Baptiste Jung
Is it possible to display this shortcode on single post only? and when on the main page the code will be gone?

Thanks

Apr 03 2009 15:55

If you build your theme it can be used, otherwise I would use the plugin

Apr 15 2009 19:30

Didnt work for me :(

Jul 09 2009 03:32

Just added this snippet to coding cow along with your automatic insert content into editor snippet. Both work really well together and make the entire thing completely painless. :)

This blog is really my favorite WP development resource! Keep it up!

Aug 18 2009 05:03

im loving this blog haha, i was looking for this without the need of a plugin!

Jan 27 2010 08:33

Hey how do I make use of the function in a template, i don’t want to type [related_posts] for every article I make :D

May 20 2010 10:59

GREAT idea – but how can I put this into the template so it appears on every post be default?

Aug 02 2010 19:10

@Finn, maybe like this (put this in php tag):

do_shortcode(‘[related_posts]‘); OR
echo do_shortcode(‘[related_posts]‘);

And to change limit :

do_shortcode(‘[related_posts limit=3]‘); OR
echo do_shortcode(‘[related_posts limit=3]‘);

Not yet tested

Aug 25 2010 05:22

Great Code! Thanks for sharing!

@Aysseline

echo do_shortcode(‘[related_posts]‘);
OR
echo do_shortcode(‘[related_posts limit=3]‘);

Works fine in template ;)

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required