Related Blog Articles – Why and How

Why add a related articles section to your blog?

If your readers like what they have just read, it gives them an easy way to navigate to other articles they may like. At the same time, it gives you more page-views, longer visits, and may even get you repeat visitors.

1. How to Add a Related Articles Section

In an ideal world, it would be great to obtain a set of related articles from Google Custom Search. However, you can only do this is you subscribe to their business license. If you have free custom search, it is against their TOS to scrape custom search engine results in this manner.

Since Google Custom Search is not an option, I went looking for available WordPress plugins. There seem to be a variety of plugins that fulfill this task, but based on the postings I came across, one of the most highly regarded related articles plugin is YARPP (Yet Another Related Posts Plugin) by mitcho.

2. Rendering Related Articles as a Gallery

YARPP supports a variety of rendering templates, but what I really wanted was to display the set of related posts as a post gallery, using my gallery plugin, and the WordPress gallery shortcode.

For example -

[gallery related="1" type="noobslide_nativex" numberposts="3"]

Related Articles

[Related post gallery rendered with the Shiba Gallery Plugin]

To render YARPP results as a gallery, it is easiest to use the query_posts command and order the results based on the YARPP scoring system.

$yarpp_time = TRUE; // get ready for YARPP TIME!
				
yarpp_cache_enforce(array('post'),$post->ID);
$related_args = array( 	'p' => $post->ID,
			'order' => 'DESC',
			'orderby' => 'score' );
$related_query = new WP_Query();
$related_query->query($related_args);
				
$attachments = array(); $i = 0;
foreach ($related_query->posts as $related_post) {
	if  (($related_post->post_type == 'page') || ($related_post->post_type == 'post')) {
	$attachments[] = $related_post; $i++;
	if ($i	>= $numberposts) break;
	}
}	
$yarpp_time = FALSE;

Line 3yarpp_cache_enforce is necessary to ensure that proper results are returned by YARPP.

Lines 4-8 – Get related articles ordered from most relevant to least.

Lines 10-16 – Filter the articles returned based on post type and limit the number of articles shown.

For detailed instructions on how to write a gallery plugin, refer to How to Render Your Own WordPress Gallery.

3. Fixing the $wp_filter Global Variable

Running the code above from within a gallery shortcode, however, can become problematic.

The yarpp_cache_enforce function operates on the $wp_filter global variable, and alters its internal array pointer.

Since the gallery shortcode is executed from within a $wp_filter['the_content'] call, we will be calling yarpp while we are still within a $wp_filter array loop. To make sure that everything works as it should, we must save our global $wp_filter state.

// MUST save state of global $wp_filter because we are currently in a $wp_filter loop
$state = key($wp_filter['the_content']);				

// query_post code here ...

// Restore wp_filter array back to its previous state
reset($wp_filter['the_content']);			
while(key($wp_filter['the_content']) != $state)
	next($wp_filter['the_content']);

4. Return Related Posts and Pages

Finally, YARPP seems to only return related posts for post objects and related pages for page objects. This seems to be the case no matter what you set the Cross-relate posts and pages? option to under Settings >> YARPP.

Since I always want to return both related posts and pages, I add a filter to the post_where hook in my plugin or theme functions.php file.

add_filter('posts_where','shiba_where_filter', 50);

function shiba_where_filter($arg) {
	global $yarpp_time;
	if ($yarpp_time && (strpos($arg, "yarpp.score") !== FALSE)) { 
		$arg = str_replace("AND wp_posts.post_type = 'page'", "", $arg); // YARPP filter
		$arg = str_replace("AND wp_posts.post_type = 'post'", "", $arg); // YARPP filter
	}
	return $arg;
}

Line 1 – Add post_where filter hook. The priority (argument 3) should be > default priority which is 10. This ensures that our filter runs AFTER the YARPP post_where filter.

Line 5 – Only filter when we are in yarpp mode.

Lines 6-7 – Remove post_type checks. This will allow our yarpp query to return all objects regardless of type.

5. Add Related Articles Gallery to Every Page

Finally, we want to add our new and shiny related articles gallery to every blog page.

add_filter('the_content', 'add_related_content');

function add_related_content($content) {
	global $post;
	
	if (($post->post_type != 'post') && ($post->post_type != 'page')) return $content;
	
	if (function_exists('yarpp_related')) {
		// Replace <> brackets with square shortcode brackets in the line below
		$addStr .= "<gallery related='1' numberposts='3' type='noobslide_nativex'>\n";
		$content .= $addStr;
	}	
	return $content;
}

We Are Done!

We now have a Related Articles Gallery!

Related Articles

Comments

  1. Amba Junior says

    Is it possible to show related articles from the same tag, using this snippet. Please let me know. Thanks for the nice snippet :-)

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>