Custom Query: Related Posts by Shared Tag Amount (21 posts)

  1. Leo Blanchette
    Posted 2 years ago #

    Lets say on average your custom post type has at least 25 tags, and usually up to 50.

    Its not enough to find "related" posts by simply whether or not they share the same tags, but instead you'd want to rank them according to how many tags they share.

    I can't seem to do this by common WP_query() methods...I think I might need a whole custom query.

    Unfortuantely I'm not familiar enough with WP's tables to write a query that sophisticated.

    Anyone have any ideas how to do this?

  2. keesiemeijer
    Posted 2 years ago #

    Try the following. Put this in your theme's functions.php: http://pastebin.com/NnDzdSLd

    Now you can use the function "get_related_tag_posts_ids()" in your template files to retrieve the related post ids based on shared tags. The function runs many queries (depending on the amount of tags for the post and posts that have a related tag assigned to it), so it's recommended to use it only in single.php, especially because your posts can have 50 tags.
    Example of how to use it in your theme template files (inside the loop):

    // get 5 related posts
    $related = get_related_tag_posts_ids( $post->ID, 5 );
    if ( $related ) {
    	$args = array(
    		'post__in'      => $related,
    		'orderby'       => 'post__in',
    		'no_found_rows' => true, // no need for pagination
    	$related_posts = get_posts( $args );
    	if ( $related_posts ) {
    		echo '<h3>Related Posts</h3>';
    		echo '<ul>';
    		foreach ( $related_posts as $related_post ) {
    			echo '<li><a href="' . get_permalink( $related_post ->ID ) . '">' . $related_post->post_title . '</a></li>';
    		echo '</ul>';

    A custom sql query would be better than this solution tough.

    consider creating a child theme instead of editing your theme directly - if you upgrade the theme all your modifications will be lost.

  3. Leo Blanchette
    Posted 2 years ago #

    My only problem now is that I don't have any text control options in this forum to make a really really big "THANK YOU".

    Totally cool. Vote this up, sticky it, benefit many future generations of WP coders.

  4. Leo Blanchette
    Posted 2 years ago #

    So you advise using this in "single.php" to keep resource use down. "single-image.php" where my custom post type --- would presumably work the same?

  5. keesiemeijer
    Posted 2 years ago #

    Yes, every template where related posts for a single post is displayed is ok. Let me explain what the function does.

    1) get all the tags for a post (query)
    2) get all posts that have any of these tags (query) (can be 1 posts or 1000 posts)(this can be limited)
    3) loop through these posts and get all tags assigned (multiple queries for tags)
    4) loop throug tags and check if the tag is in the tags for the post (no queries).

    As you can see there will be a lot of queries to the database if you want to show related posts for multiple posts.

    I, therefore think this is not a very clean solution to your problem. I've tried to optimize the queries to be as light as possible but maybe it's also possible with a single custom sql query.

    Another way to remedy this problem would be to update the database with the related posts (for all the posts) anytime you publish or update a post.

  6. Leo Blanchette
    Posted 2 years ago #

    Yes, the last thing you say is what I intended to do. My other theme (where I made my own database tables) had a rather big query that performed this operation all in one hit.

    I'm simply going to let the user decide when to update their related images (posts) - or perhaps run a chron job...each post will have a meta value having the list of related images :D.

    Just having a decent function is enough though. There will often be thousands of posts (images) to loop through, so its best to pre-run it.

    Great job on the function. I'm sure its going to help lots of people.

  7. keesiemeijer
    Posted 2 years ago #

    Moving it to the backend and/or running a cron job are good ideas. To even optimize the queries further you could use 'cache_results' => false for the get_post() function:

    Maybe looking at the transient api is also an idea:

    I'm glad you have some sort of a solution.

  8. Leo Blanchette
    Posted 2 years ago #

    This code you gave me was probably the best thing I've ever gotten off of this forum - I had to make some slight modifications to the custom post type I was using, but here it is in action on a few user sites:




    As you can see it works flawlessly. I credited you :D

  9. keesiemeijer
    Posted 2 years ago #

    I finally got around making that custom sql query. I've made it into a plugin: http://wordpress.org/extend/plugins/related-posts-by-taxonomy/
    See the documentation on how to use the function that queries for the related posts. This only adds a few database queries per post (no matter how many tags), so now you can use it on other templates as well.

  10. Leo Blanchette
    Posted 2 years ago #

    Thats really good - very valuable. At this time there are about 30 sites that will benefit from that! Much appreciated.

  11. Leo Blanchette
    Posted 2 years ago #

    My theme shows image results and other specialized stuff, so I'm going to integrate your plugin as part of the theme. But I'm going to give credit to you in the admin area where its used and the credits area.

  12. Leo Blanchette
    Posted 2 years ago #

    Correction - it looks like you give directions on using it! There is nothing to modify. Great job.

  13. Leo Blanchette
    Posted 2 years ago #

    Not to be annoying, but I just have to say this is a real masterpiece, especially for theme integration. I literally don't have to do much at all except write some custom output through a template.

    I'm going to have this plugin packed into the theme and deploy/activate itself at install.
    Great job.

  14. Leo Blanchette
    Posted 2 years ago #

    So far so good. I noticed it does not look for my custom taxonomies? Also it does not show up on my cpt page. But plugging away at it and should eventually get it working.

  15. keesiemeijer
    Posted 2 years ago #

    I noticed it does not look for my custom taxonomies?

    What are you using, the widget, shortcode or function? Did you register your custom taxonomy to be public? Do the custom taxonomies show in the widget dropdown?

  16. keesiemeijer
    Posted 2 years ago #

    Maybe it's because you include the plugin in your theme and activate it before your theme has set up the custom taxonomy and post type.
    See how you can include things after a theme is set up:

  17. Leo Blanchette
    Posted 2 years ago #

    Just got back - that might be it. But you made a very good documentation on using the functions anyway - check this out -


    Bottom of page - its working great. Lots of other sites will benefit too.

    I'll look at everything you stated in the meantime.

  18. nathanadams
    Posted 1 year ago #

    Hi keesiemeijer,

    I'm trying to use your function that you wrote above (as opposed to the plugin) and I can't seem to get any results.

    I'm trying to use it on the single pages for a custom post type ('projects'), against a custom taxonomy ('industry'). (If I could match against a second taxonomy, 'discipline', that would be even better, but not necessary).

    I've tried modifying the tax_query array within the function to

    'tax_query'      => array(
                'post_type' => 'projects',
                'taxonomy' => 'industry',
                'field'    => 'id',
                'terms'    => $tag_ids,
                'operator' => 'IN'

    as well as changing wp_get_post_tags to wp_get_post_terms, but no change makes any difference.

    The reason I want to use the function rather than the plugin as I have some very specific formatting I want for the results (as well as referencing some ACF values).


  19. keesiemeijer
    Posted 1 year ago #

    Try it with wp_get_post_terms()

    Here is a modified version for your 'industry' taxonomy:

    Another way to get the related posts is to use the functions from the plugin.

    consider creating a child theme instead of editing your theme directly - if you upgrade the theme all your modifications will be lost.

  20. Nathan Adams
    Posted 1 year ago #


    I still couldn't get a result using the modified version you posted, but I managed to get it working using the functions from the plugin (I completely missed that when I looked at the documentation earlier, sorry about that) and making sure the post type was included in the arguments.

    Thanks also for the tip on child themes. It's not necessary on this particular project as the entire theme is a custom one from scratch, but will note it for other projects.

  21. keesiemeijer
    Posted 1 year ago #

    You're welcome :)

Topic Closed

This topic has been closed to new replies.

About this Topic