Shiba

Adventures in WordPress

  • — Home —
  • Dog
  • Art
  • Contact
  • WordPress Articles
    • WP Plugins
    • WP Programming
    • WP Admin Panels
    • WP Theme Design
    • WP How-To
    • WP Theme Images
You are here: Home / WordPress Programming / Related Blog Articles – Why and How

Related Blog Articles – Why and How

Tweet

by ShibaShake 1 Comment

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

<< Previous Next >>

WordPress Blog How-To

<< Previous Next >>

Optimize Your WordPress Plugins with Tags

Shows how you can enhance page speed by using tags to selectively run plugins only when needed. Page speed is important because it affects Google Page Rank and user experience.

<< Previous Next >>

Add Tags and Categories to Your WordPress Page

Currently, post-tags and post-category metaboxes only appear in the Edit Post screen. We consider how to add these metaboxes into the Edit Page screen, as well as properly save our results.

< Playback Stop Play >
WordPress Blog How-To
Optimize Your WordPress Plugins with Tags
Add Tags and Categories to Your WordPress Page

[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 3 – yarpp_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

WordPress Blog How-To

Optimize Your WordPress Plugins with Tags

Shows how you can enhance page speed by using tags to selectively run plugins only when needed. Page speed is important because it affects Google Page Rank and user experience.

Add Tags and Categories to Your WordPress Page

Currently, post-tags and post-category metaboxes only appear in the Edit Post screen. We consider how to add these metaboxes into the Edit Page screen, as well as properly save our results.

Comments

  1. Amba Junior says

    May 28, 2013 at 11:27 pm

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

    Reply

Leave a Reply to Amba Junior Cancel reply

Your email address will not be published.

Recent Posts

  • Screen-shot of mobile responsive Poll Daddy object, where text floats properly to the right of radio buttons.How to Make Poll Daddy Objects Mobile Responsive
  • Screen-shot of blog post with no page border (flowing design).Genesis Skins 1.5
  • Screen-shot of the media manager Create-Gallery screen, while doing a post search.Shiba Media Library 3.7
  • Screenshot of the Edit Gallery screen after we hit the Create Gallery button.How to Expand the WordPress Media Manager Interface
  • Blonde girl looking through and holding a circular picture frame.Shiba Gallery 4.3
  • Close-up of beautiful blonde holding a square picture frame.Google Authorship - Good or Bad for Search Traffic?
  • Shiba Widgets 2.0
  • Media Temple screenshot of editing my sub-domain DNS entry.Using CDN Cnames with w3tc and MultiSite
  • Shiba Skins WordPress ThemeShiba Skins WordPress Theme
  • How to add the Media Manager Menu to the Theme Preview InterfaceHow to Add the Media Manager Menu to the Theme Preview Interface

Recent Comments

  • Populate our Edit Gallery menu using a gallery shortcode.How to Add the WordPress 3.5 Media Manager Interface – Part 2 (29)
    • Janine
      - Still relevant in 2019.
  • Update custom inputs with the proper data using Javascript.Expand the WordPress Quick Edit Menu (57)
    • PhoenixJP
      - Thanks for this tutorial. Does someone knows if this still work with wordpress 5.03 and 5.1.
    • Francine Carrel
      - This is a very long time away from your original comment, but did you ever work it out? I am stuck on the exact same thing ...
  • WordPress Search Widget – How to Style It (55)
    • TelFiRE
      - How do you style the "X" that shows up when you start typing?
  • WordPress Excerpt – How to Style It (36)
    • James
      - Great post. I really need some help. I have set border lines around my excerpts on my blog page/post page. The problem is ...
  • Add Custom Taxonomy Tags to Your WordPress Permalinks (123)
    • Darshan Saroya
      - Update permalinks. Go to settings > permalink and just save it.
    • Darshan Saroya
      - I want to access two different types of taxonomies like city and room, how can I access it via wp permalink?
  • How to Selectively Load Plugins for Specific Pages (6)
    • cla
      - Perfect! But at first I was misled, I thought the path / wordpress-theme / was an your alias of / theme .. and nothing happened.. ...
    • Aeros
      - Hi, I have tried your way. My problem is i'm using boilerplate to most of my plugins. When i tried to include the plugin ...
  • Write a Plugin for WordPress Multi-Site (44)
    • An Quach
      - I always use single site because it's easy for me to managed. When I need another worpdress on subdomain or subfolder, I ...

Copyright © 2019 · Genesis Skins by ShibaShake · Terms of Service · Privacy Policy ·