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

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"]
No related results - YARPP plugin not installed.

[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!

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

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

Recent Posts

  • Screenshot of an example article in code view of a modified Gutenberg editor.How to Harness the Power of WordPress Gutenberg Blocks and Combine It with Legacy Free-Form Text
  • Screenshot of the Success, WordPress has been installed page.Migrating Your WordPress Website to Amazon EC2 (AWS)
  • Screenshot of WinSCP for creating a SFTP configuration.How to Set-Up SFTP on Amazon EC2 (AWS)
  • WordPress Gutenberg code view screenshot of this article.How to Prevent Gutenberg Autop from Messing Up Your Code, Shortcodes, and Scripts
  • Screenshot of the Success, WordPress has been installed page.How to Create a WordPress Website on Amazon EC2 (AWS)

Recent Comments

  • Screenshot of the Success, WordPress has been installed page.How to Create a WordPress Website on Amazon EC2 (AWS) (1)
    • Erik
      - Great article. All worked great except for this step:apt install php-mysqlChanging to this fixed it:apt install ...
  • Add Custom Taxonomy Tags to Your WordPress Permalinks (125)
    • Anthony
      - Where does this code go? Like, what exact .php file please?
  • Screenshot of an example article in code view of a modified Gutenberg editor.How to Harness the Power of WordPress Gutenberg Blocks and Combine It with Legacy Free-Form Text (1)
    • tom
      - hi,my experience was like the same, but for me as theme developer the "lazy blocks"(https://wordpress.org/plugins/lazy-blocks/) ...
  • WordPress Custom Taxonomy Input Panels (106)
    • Phil T
      - This is unnecessarily confusing. Why declare a variable with the same name as your taxonomy? Why did you choose a taxonomy ...
  • Create Pop-up Windows in Your WordPress Blog with Thickbox (57)
    • Jim Camomile
      - I have used this tutorial several times and it is one of the few simple and effective ways to add popups with dynamic content, ...

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