Pippins Plugins
  • Email
  • Facebook
  • Feedburner
  • Github
  • Google
  • Twitter
  • Vimeo
  • Youtube
  • Rss
  • About
  • News
  • Join the Site
    • Member Benefits
    • Member Plugins
    • Email Notifications
  • Plugin Store
    • Affiliate Area
    • Checkout
  • Plugins
    • Plugin Portfolio
      • Plugin Portfolio – List View
    • Free
    • Premium
    • Member Plugins
    • Coding Standards
    • Get Plugin Support
  • Tutorials
    • Series
      • Plugin Development 101
      • Creating a User Follow System Plugin
      • Customizing Restrict Content Pro
      • Displaying Content with Easy Content Types
      • Writing Your First WordPress Plugins, Basic to Advanced
      • Working with Widgets
      • User Submitted Image Galleries
      • Plugin Thoughts
      • Integrating Stripe.com with WordPress
      • WordPress Rewrite API
    • Member Exclusive
      • Free Members
      • Subscriber Only
    • Difficulty
      • Beginner
      • Intermediate
      • Advanced
    • Action and Filter Hooks
    • Ajax
    • Custom Post Types
    • External APIs
    • Short Codes
    • Taxonomies
    • Video Tutorials
    • Widget Tutorials
    • WordPress Admin / Dashboard
    • Working with jQuery
    • WordPress Database
    • Writing Plugins
    • Tag Index
  • Reviews
  • Support Forum
  • Contact
    • Support the Site
    • Request Code Review
    • Plugin Support

Write a Better Related Posts Plugin for Custom Taxonomies

Posted on May 16, 2011 by Pippin in Advanced, Taxonomies, Tutorials, Widget Tutorials, Writing Plugins 14 Comments
Home» Tutorials » Advanced » Write a Better Related Posts Plugin for Custom Taxonomies
Tweet
Love It - 0

Related Posts Plugins are very popular as a method for WordPress users to display related content at the end of their posts, providing the reader with additional relevant content. Typically, related posts plugins use Post Tags to compare posts and find those that are related to the currently displayed post. The problem with this method is that it doesn’t work for any post type that doesn’t use Post Tags or that has custom taxonomies.

You may download the plugin version of this tutorial for free here

So what we are going to do here is write a simple plugin that will greatly improve the relevancy of our related posts. We are also going to make it possible to utilize custom taxonomies as a comparison tool.

Because we are going to be using custom taxonomies as our comparison base, we will use the tax_query parameter of query_posts. This parameter is rather complex, so I’m not going to go into detail about it, but you can read my tutorial at WP Mods for a more detailed explanation.

1 – Setup The Plugin File

Our plugin is going to consist of just a single file with just one function inside of it. First, we need to define the plugin header:

1
2
3
4
5
6
7
8
/*
Plugin Name: Related Posts by Taxonomy
Plugin URI: http://pippinspages.com/related-posts-by-taxonomy
Description: Adds a related posts section to your posts that displays those related by custom taxonomies
Version: 1.0
Author: Pippin Williamson
Author URI: http://pippinspages.com
*/

This simply tells WordPress about our plugin.

2 – Begin Our Related Posts Function

Defining our function is simple, just the function name and one parameter.

1
2
3
function pippin_related_posts($taxonomy = '') {
    // our function code will be here
}

3 – The Body of Our Function

The rest of the code for our function will replace

// our function code will be here

We will begin by defining a global variable for the $post object, a default taxonomy of Post Tags, and we will also retrieve a list of all of the terms set to our current post.

1
2
3
4
5
global $post;
 
if($taxonomy == '') { $taxonomy = 'post_tag'; }
 
$tags = wp_get_post_terms($post->ID, $taxonomy);

A very important next step is to include a condition check that will cause the next couple of steps to only run if the wp_get_post_terms() function does not return empty.

1
2
3
if ($tags) {
   // the next couple of steps go in here
}

We now have a variable called $tags that is holding all of the terms applied to the current post. The next step is to setup the arguments that we will pass to our get_posts() function, which will query the posts that are considered related.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$first_tag 	= $tags[0]->term_id;
$second_tag = $tags[1]->term_id;
$third_tag 	= $tags[2]->term_id;
$args = array(
	'post_type' => get_post_type($post->ID),
	'posts_per_page' => 4,
	'tax_query' => array(
		'relation' => 'OR',
		array(
			'taxonomy' => $taxonomy,
			'terms' => $second_tag,
			'field' => 'id',
			'operator' => 'IN',
		),
		array(
			'taxonomy' => $taxonomy,
			'terms' => $first_tag,
			'field' => 'id',
			'operator' => 'IN',
		),
		array(
			'taxonomy' => $taxonomy,
			'terms' => $third_tag,
			'field' => 'id',
			'operator' => 'IN',
		)
	)
);

Notice that I have setup three variables, one for each of the first three tags (or terms) applied to the post. These three tags are how we will consider a post to be related. In order to find the related posts, or others that have the same tags applied to them, I have setup a rather complex tax_query that makes the get_posts() function only look for posts that have these tags. As I mentioned above, the tax_query parameter is rather complicated, so please read the articles linked at the top for more info.

The next step is to setup the actual get_posts() call, which will display our related posts.

1
2
3
4
5
6
7
8
9
10
11
12
 
$related = get_posts($args);
if( $related ) {
	$temp_post = $post;
		foreach($related as $post) : setup_postdata($post);
			$content .= '<ul class="related-posts-box">';
				$content .= '<li><a href="' . get_permalink() . '" title="' . get_the_title() . '">' . get_the_title() . '</a></li>';
			$content .= '</ul>';
 
		endforeach;
	$post = $temp_post;
}

Notice how I have setup a temporary variable called $temp_post and set it equal to $post, and at the end of the foreach loop I have reset the $post variable back to its original state by setting it equal to $temp_post. This is very important because it ensures that we don’t cause any conflicts with the currently displayed post’s content.

Now, there is just one more step in the function writing process. Put this next line after the closing } of the if ($tags conditional check.

1
return $content;

That’s it!

3 – Our Final Plugin Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Plugin Name: Related Posts by Taxonomy
Plugin URI: http://pippinspages.com/related-posts-by-taxonomy
Description: Adds a related posts section to your posts that displays those related by custom taxonomies
Version: 1.0
Author: Pippin Williamson
Author URI: http://pippinspages.com
*/
 
function pippin_related_posts($taxonomy = '') {
 
global $post;
 
if($taxonomy == '') { $taxonomy = 'post_tag'; }
 
$tags = wp_get_post_terms($post->ID, $taxonomy);
 
	if ($tags) {
		$first_tag 	= $tags[0]->term_id;
		$second_tag = $tags[1]->term_id;
		$third_tag 	= $tags[2]->term_id;
		$args = array(
			'post_type' => get_post_type($post->ID),
			'posts_per_page' => 4,
			'tax_query' => array(
				'relation' => 'OR',
				array(
					'taxonomy' => $taxonomy,
					'terms' => $second_tag,
					'field' => 'id',
					'operator' => 'IN',
				),
				array(
					'taxonomy' => $taxonomy,
					'terms' => $first_tag,
					'field' => 'id',
					'operator' => 'IN',
				),
				array(
					'taxonomy' => $taxonomy,
					'terms' => $third_tag,
					'field' => 'id',
					'operator' => 'IN',
				)
			)
		);
		$related = get_posts($args);
		if( $related ) {
			$temp_post = $post;
				foreach($related as $post) : setup_postdata($post);
					$content .= '<ul class="related-posts-box">';
						$content .= '<li><a href="' . get_permalink() . '" title="' . get_the_title() . '">' . get_the_title() . '</a></li>';
					$content .= '</ul>';
 
				endforeach;
			$post = $temp_post;
		}
	}
	return $content;
}

4 – Displaying Our Related Posts

To display the related posts, place this inside your single.php loop:

1
echo pippin_related_posts();

This will display an unordered list of four related posts.

If you want to display posts related by a custom taxonomy, such as “Genres”, then you can do this:

1
echo pippin_related_posts('genres');

If coding isn’t quite your thing, you can download the complete plugin for free here.

Tweet Follow @pippinsplugins
Related posts, taxonomy, tax_query

14 comments on “Write a Better Related Posts Plugin for Custom Taxonomies”

  1. Emile Jobity says:
    September 22, 2011 at 3:40 pm

    awesome very helpful indeed. thanks.

    Reply
    • Pippin says:
      September 22, 2011 at 3:43 pm

      @Emile – Excellent. Glad it was helpful.

  2. Sophia Kaylee says:
    November 11, 2012 at 10:48 am

    This post really help to me to create custom tags in WordPress thanks

    Reply
  3. Miha says:
    December 11, 2012 at 3:38 am

    Hi,
    Great plugin!

    i would like to modify it in a way to use more than one taxonomy as related post filter…

    Also as a suggestion, I would give a visitor an option to “checkbox” select which taxonomies want to be included in the related posts…

    Lets say user is viewing the post with taxonomies (car type, brand,condition etc)
    1. By default (show all or, all checked checkboxes) it should show all related posts to all taxonomies of current post (even better would be if this could also be specified in options, so we could select which taxonomies to use as related)

    2. Visitor should be able to “uncheck” the taxonomy that they don’t want to use in related posts, so when the Post from taxonomies “Car – Ford – new” is viewed, user should be able to “uncheck” – condition taxonomy and get also used cars related to this post…

    - Also using post type with custom taxonomies as filter for related posts would be great feature!

    Hope you see it useful and it will be done.. if not, could you please point me where to start to achieve this?

    Thanks!
    cheers!

    Reply
    • Pippin says:
      December 11, 2012 at 1:59 pm

      The tax_query parameter for WP_Query allows you to query on multiple taxonomies, so you will want to use that. Note: querying by multiple taxonomies has a significant impact on performance.

  4. George Stephanis says:
    February 2, 2013 at 7:56 pm

    Instead of hardcoding and expecting at least three array indices in the tags, maybe iterate through and use all of them like — (I also added post__not_in to omit the original from being related to itself)


    if ( $tags = wp_get_post_terms( get_the_ID(), $taxonomy ) ) {
    $args = array(
    'post_type' => get_post_type( get_the_ID() ),
    'post__not_in' => array( get_the_ID() ),
    'posts_per_page' => 5,
    'tax_query' => array( 'relation' => 'OR' ),
    'orderby' => 'rand',
    );
    foreach ( $tags as $tag ) {
    $args['tax_query'][] = array(
    'taxonomy' => $taxonomy,
    'terms' => $tag->term_id,
    'field' => 'id',
    'operator' => 'IN',
    );
    }
    }

    Reply
    • Pippin says:
      February 4, 2013 at 11:36 am

      Nice enhancement, thanks :)

  5. hiphopinenglish says:
    February 17, 2013 at 8:14 am

    Hi Pippin.
    Great work here, thanks. One question: How can I split up line 14 to include my taxonomy (which is the only form of tagging posts I use on a custom post type) and ‘post_tag’, used on normal post types, to which my custom taxonomy also applies.
    Complicated?
    To be clear:
    I have a custom taxonomy ‘hhie_artists’ which is used on ‘posts’ and CPT ‘hhie_artists’. ‘hhie_lyrics’ only uses ‘hhie_artists’ (no tags), but normal posts in category “Releases” use ‘hhie_artists’ AND tags. I would like to incorporate `$taxonomy = ‘post_tag’ && ‘hhie_artists´ if this is possible.
    Thanks. Joe

    Reply
    • Pippin says:
      February 20, 2013 at 6:08 pm

      Joe, I”m sorry but I don’t understand your question :D

  6. hiphopinenglish says:
    February 21, 2013 at 5:39 am

    I knew I’d worded that badly! What I would like is to incorporate a Custom Taxonomy and regular Post Tags as our related terms. This is because one of our CPTs only uses a custom taxonomy (no post tags), and our “normal Posts” use the custom taxonomy AND post tags. Does this make more sense?

    Reply
    • Pippin says:
      February 25, 2013 at 7:22 pm

      Yes, that makes sense :) All you need to do is set the relation to “AND”:

      'relation' => 'AND'
      
  7. Tom says:
    April 1, 2013 at 9:41 pm

    Hi Pippin,

    I attempted to use this without the plugin. With the plugin and I am receiving this error: “Fatal error: Cannot use object of type WP_Error as array in”.

    My goal is to show related tags from my custom taxonomy “intags” and for my custom post type “insights”. I added “intags” to the first line of your code and when I echoed out the function I added “insights” as per you example. Any thoughts?

    Reply
  8. Miha says:
    April 17, 2013 at 3:31 am

    I tried to create a widget with options to select “category or tag” as first taxonomy AND “custom taxonomy” for second one (if empty only first should be used for relation)…

    It could then show posts from same category AND with same custom taxonomy, in my case I would like to display posts from same category on the same location * custom taxonomy.

    It doesn’t seem to be so complicated to achieve this, but I still had no luck.

    Any help?

    Thank you!

    Reply
    • Pippin says:
      April 17, 2013 at 7:02 pm

      Can you show me some of the code you have?

Leave a Reply Cancel reply

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

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>

  • Login

Lost your password?

Please enter your username or e-mail address. You will receive a new password via e-mail.

  • Facebook Become a Fan Like

  • Twitter Subscribe on Twitter Follow

  • YouTube Follow my Videos Subscribe

  • RSS Feed Subscribe with RSS Subscribe

Easy Digital Downloads

Most Loved

  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages
  • Simple Notices Pro Plugin for WordPress
  • User Bookmarks for WordPress
  • Front End Registration and Login Forms Plugin

Similar Plugins and Posts

  • Custom Taxonomy Friendly Archives
  • User Submitted Image Gallery – Part 5
  • Password Protect Taxonomy Terms and All Posts in the Terms
  • Adding Custom Meta Fields to Taxonomies
  • Filter Posts by Custom Taxonomy in Admin

Latest Premium Content

  • Plugin Development 101 – Introduction to Adding Dashboard Menus
  • Plugin Development 101 – Intro to Loading Scripts and Styles
  • User Follow System – Part 5
  • Plugin Development 101 – Intro to Short Codes
  • Plugin Development 101 – Registering a Custom Post Type
  • Plugin Development 101 – Intro to Actions

Latest Tutorials

  • Submitting Your First Pull Request to a WordPress Plugin on Github (4)

    Github is an extremely popular tool for managing WordPress plugins, and one...

  • Plugin Development 101 – Introduction to Adding Dashboard Menus (1)

    Adding new menus, both top level and sub level, to the WordPress Dashboard is a really common task for plugins...

  • Plugin Development 101 – Intro to Loading Scripts and Styles (16)

    In this part of Plugin...

Enter your email to receive automated updates when new posts are published

Latest Tweets

  • I was just interviewed by @WP_Squared. Check it out: http://t.co/aWtKOlKVfb
    May 23, 2013
  • @no_fear_inc Cool, will hope to see you there!
    May 23, 2013
  • @no_fear_inc Are you coming?
    May 23, 2013

Topics

contextual help featured get_user_meta attachments campaign monitor register_setting wp_enqueue_script hook Rémi Corson the_content shortcodes Sugar Event Calendar add_shortcode mail chimp plugin authors attachment image forms login short codes do_action Related posts comments recent posts post types apply_filters bbpress short code taxonomies custom post type images gallery Ajax Stripe taxonomy jquery users widgets add_filter easy content types add_action widget restrict content pro easy digital downloads

Weekly Newsletter

Useful Links

  • Join the Site
  • Plugin Store
  • Affiliate Area
  • Tag Index
  • Support the Site
  • Suggest a Tutorial
  • Random Post
  • Contact

Monthly Archives

(c) 2013 Pippin's Plugins