Categories: Tutorials

How to show related posts using custom taxonomy in WordPress

For one of my customer websites, I needed to build a query showing related posts (to the currently opened post) from different categories using thumbnails that showed the title on mouseover (hover).

To boot, a user-friendly way to enter new posts into the query was in order, as my customer would need to be able to do this themselves.

The basic idea was that there were posts in a project-portfolio (projects), types of systems (systems) and manners of application (applications). Each project shown as current item would require a sidebar showing all relevant systems and applications and the other ways around).

I started out by creating the posts in categories and subcategories, but this was too limited. Since each post was in one parent category but in multiple sub categories (with different parents) It was very hard to filter the query and show only the posts from a specific parent category.

The second option was parent categories combined with tags. This worked better, and I found a script that got me quite far, written by WordPress forum members MichaelH and fine-tuned by Carl-Johan ( read article on WordPress forum here):

<h3 class="title-projects">projects</h3>

<?php global $post; //query all posts
  $nextTagThumb='-1';
  $yourCategory = '5'; //query category 5 (projects category)
  $saved_ids = array();
  $saved_ids[] = get_the_ID(); //make post ID list of all posts output by the query
  $tags = wp_get_post_tags($post->ID); //get all tags from the current post
  
  // build array of tag ID's
  $tagids = array();
  foreach ($tags as $tag)
  {
    $tagids[] = $tag->term_id;
  }
?> 

<?php
  if ($tags) {
  $what_tag = $tags[($nextTagThumb+'1')]->term_id; //term_id is the tag id
  $args=array(
  'category__in' => array($yourCategory),
  'tag__in' => $tagids,
  'post__not_in' => $saved_ids, 
  'showposts'=>20,
  'caller_get_posts'=>1
  );
  $my_query = new WP_Query($args); //custom query to display all posts that match the $args parameters
  if( $my_query->have_posts() ) {
  while ($my_query->have_posts()) : $my_query->the_post(); 
?>

<li class="post-<?php the_ID(); ?>"> <!-- create list loop of all posts output by the query -->
  <a href="<?php the_permalink() ?>" rel="bookmark" title="Link naar <?php the_title_attribute(); ?>">
    <span class="sidebar-post-title"><?php the_title(); ?></span> <!-- show post title -->
    <span class="sidebar-post-thumb">
    <img src="<?php echo get_post_meta($post->ID, "sidebar-thumb", true);?>" />
    </span> <!-- show post thumbnail -->
  </a> 
</li>

<?php endwhile;
  }
  wp_reset_query();
  $nextTagThumb = ($nextTagThumb+1);
  }
?>
Now only a few problems remained:
  1. Filtering the tags per category. This posed a challenge: as there was no actual connection between categories and the tags, the results from the query showed not only the directly related posts, but also the indirectly related posts. For example, when showing a project post with system tag 30-mm and application tag roof, the results would also show system tag 40-mm because this was a tag of the application article ‘Roof’!
  2. Adding a new post with the necessary tags was not very user-friendly, as the author would need to use the exact same tag (30-mm not 30 mm or 30mm for instance), and there was no list available in the Create Post interface.

After searching a long time for a way to filter the tags somehow, I decided a new approach was required: customization.

I didn’t know about how to go about this, but after searching the Internet for a while, I came across custom fields and custom taxonomy. I’m sure custom fields would also have been a solution, but I ended up using custom taxonomy. Once you know how it works, it’s quite easy, and it also provided a solution for the second remaning problem! Here’s how:

Added the following code to functions.php in my child theme (thanks for the code Justin Tadlock (read his article here). This creates the custom taxonomy fields in WordPress, also shown in the WordPress administrator (see screenshot):

<?php
// Create custom taxonomies for right sidebars
add_action( 'init', 'create_my_taxonomies', 0 );

function create_my_taxonomies() {
 register_taxonomy( 'systems', 'post', array
        ( 'hierarchical' => true, 'label' => 'Systems', 'query_var' => true, 'rewrite' => true ) );
 register_taxonomy( 'applications', 'post', array
       ( 'hierarchical' => true, 'label' => 'Applications', 'query_var' => true, 'rewrite' => true ) );
 register_taxonomy
       ( 'projects', 'post', array( 'hierarchical' => true, 'label' => 'Projects', 'query_var' => true, 'rewrite' => true ) );
} ?>
And the following code to single.php. The last part of the script ensures the thumbnail is used to show the post (I created a custom field in all posts containing the path to the thumbnail image):
<h3 class="title-projects">projects</h3>

<?php
global $post;
$terms = get_the_terms( $post->ID , 'projects', 'string');
$do_not_duplicate[] = $post->ID;
 
if(!empty($terms)){
    foreach ($terms as $term) {
        query_posts( array(
        'projects' => $term->slug,
        'category__in' => 5, // 5 being the projects category 
        'showposts' => 80,
        'caller_get_posts' => 1,
        'post__not_in' => $do_not_duplicate, //exclude the current item
        'orderby'=>title,
        'order'=>ASC
         ) );
         
        if(have_posts()){
            while ( have_posts() ) : the_post(); $do_not_duplicate[] = $post->ID; ?>
                <li class="post-<?php the_ID(); ?>"> <!-- create list loop of all posts output by the query -->
              <a href="<?php the_permalink() ?>" rel="bookmark" title="Link naar <?php the_title_attribute(); ?>">
                <span class="sidebar-post-title"><?php the_title(); ?></span> 
                <!-- show post title, used css to reveal only on hover -->
                <span class="sidebar-post-thumb">
                <img src="<?php echo get_post_meta($post->ID, "sidebar-thumb", true);?>" />
                </span> <!-- show post thumbnail -->
              </a> 
            </li>
            <?php endwhile; wp_reset_query();
        }
    }
}
?>
You can see it in action here when you select any of the sub-menu items in the left sidebar menu (website is in dutch).

I hope this helps you out, maybe this will save you a lot of time searching for answers. Good luck!

This post was last modified on 26/06/2018 11:26

Boris Hoekmeijer

View Comments

  • bro help me, how can i display post related with the category by hover image with visual portfolio plugin

  • Hi, Thanks for the post. I am searching for a plugin with sort code where i can list 5 post by custom taxonomy. Each post have at least 3 to 4 custom taxonomy associated with it. Any help please.

  • Hello !

    A huge thank you for sharing this solution.
    Was looking for a solution via Codex since 2 days.

    Thank you so much !

    Lily

  • Hmm I'm kinda restricted to the theme I purchased for the project. I think I need to simplify things, perhaps by manually setting up conditional statements (If isin category xxx, then show posts from taxonomy xxx). Probably a little more work, but it supports a very dynamic sidebar and since executing php in widgets is possibly, it saves time on coding i think.

    I really thought it would be very easy to make relationships between multiple categories/taxonomies!

    Anyway thanks for thinking along, I'm glad I found your site and could bounce off some ideas :) Liked the post backup solutions too, I will check out the program Bart for synchronising with an external drive in addition to my NAS backups.

  • Perhaps you can create extra categories and add all relevant posts to the category that binds the posts? Might work, depending on the way you're using and displaying your categories.

  • Thanks Boris,

    Yes your explanation seems logical. Once the taxonomy exists, most work is done. In my case however, it seems like a lot of work: i have posts with content in certain (sub)categories which i need to link to posts in another custom post type. I think I will do some research on a shared taxonomy with keywords and hoping I find a way to pull out the content for each category.

  • Hi Boris,

    Excellent post.

    I was just wondering: Based on your code, if a user visits a post, you can specify related projects in the sidebar using the custom taxonomy. Can it also go the other way around? So when a user is visiting the project page, that it will display links pointing to the related content?

    Reason for asking is a small project i'm trying to set up. I have no clue how to organise it :)

    • Hi Kris,

      I haven't tested it, but I suppose it wouldn't be very difficult.

      What you would need is a category or taxonomy template file (category-yourcategorynumber.php) for each category/taxonomy that needs its own sidebar content, and then apply the code as I've shown.

      To then show posts from the proper categories, change the category number at $yourcategory (line 5).

      Does this help?

Share
Published by
Boris Hoekmeijer

Recent Posts

Agribusiness Service

Website en logo ontwerp voor Kookstudio Aalsmeer - voor uw kookclub, kookfeest of bedrijfsuitje in…

11 months ago

CardioThoracaal Chirurgie Zorgpad

Website en logo ontwerp voor Kookstudio Aalsmeer - voor uw kookclub, kookfeest of bedrijfsuitje in…

11 months ago

7huijzen Food Quality & Innovation Management

Website en logo ontwerp voor Kookstudio Aalsmeer - voor uw kookclub, kookfeest of bedrijfsuitje in…

1 year ago

Prime Housing

Website en logo ontwerp voor Kookstudio Aalsmeer - voor uw kookclub, kookfeest of bedrijfsuitje in…

1 year ago

Cor de Kroon

Website en logo ontwerp voor Kookstudio Aalsmeer - voor uw kookclub, kookfeest of bedrijfsuitje in…

1 year ago

Hoe leeg je de cache van je browser?

Building your WordPress website efficiently using the 10 tips I documented after years of experience.…

2 years ago