Codeable info

Display Related Posts With WordPress Shortcode

Posted on by in WordPress Tutorials

In our last tutorial we talked about keeping people interested in your WordPress blog by implementing a random post link that queries a completely random post hosted on your blog for your readers to check out. But another great way to keep readers hopping around your blog is to display related posts nearby, so that they can keep checking out posts on an interesting topic.

In the spirit of twins we’re going to use WordPress shortcode to display the related blog posts in a location of our choice. This tutorial does involve editing the “functions.php” source file for your active WordPress theme, so make sure to back up the database for good measure before continuing.

The following code must be implemented in your “functions.php” file and can be placed anywhere so long as it doesn’t break up an existing segment of code:

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;
}

Basically the above code is designed to query and display related posts based on assigned tags, so it will show posts with an identical or similar tag. In order to use the code above we need to implement one more line of code, however this code can be positioned anywhere we would like the related posts to display. For instance if you want the related posts to display in your page footer you would implement the related tag in your “footer.php” source file for the active WordPress theme.

The tag to implement the related posts section is as follows:

[related_posts]

By default the function is set to display a total of 5 related posts, so if you would like to lengthen the related display list you will need to change the above tag to the following:

[related_posts limit="#"]

Obviously you will need to change the “#” symbol to the total number of related posts you would like displayed (if you want to list 10 related posts you would change the “#” symbol to “10”).

From here on out remember one thing; since the aforementioned shortcode involves querying related post tags it would be a good practice to always use at least one existing tag on each new blog post. This will ensure that at the very least one or two related posts will display with identical tags.

Now since you’ve gotten this far you may be wondering why the Olsen twins debuted in the picture and if there is a reason they showed up to the party. The answer is no, they were just a good example of related twins (hello, related posts=related twins).

Now if you like staring at that picture you can stay for a while. Otherwise be on your merry way and enjoy the shortcode!

)
Codeable info

Comments (6)

Comment by Alex says:

They are related.. ;)

Comment by Steve says:

Ive added this after the functions code

add_shortcode(â€Ëœrelated_postsâ€â„¢, â€Ëœrelated_posts_shortcodeâ€â„¢);

but the problem persists, all that displays is the shortcode – the function does not run and show related posts. Im using this shortcode [related_posts]

Comment by AJ Clarke says:

What’s up with the Olsen twins?

Comment by Iurie says:

Can you, please, to be more explicit?

Comment by Slydawgg says:

Just so others know what to do –

After the above code, you need to add the following:

add_shortcode(‘related_posts’, ‘related_posts_shortcode’);

Comment by Slydawgg says:

This looks like a good concept, but doesn’t seem to be complete. Placed the code in my functions.php file, and called the “[related_posts]” shortcode in a page & post, and all it does is show “[related_posts}” on the screen after publishing.
Does this shortcode need to be created?

Codeable info