Gordonmac Dot Com

Mostly a web development blog

WordPress – Listing posts in same category of a custom taxonomy

Posted: June 21st, 2012 | Tags: | Posted in: PHP, Tutorials, Wordpress
Note: This tutorial was originally published in 2012. The tips and techniques explained may be outdated.

This really did my head in for a while today! I thought it would be as simple as it is to find related posts, but nope, it’s a wee bit more involved.

The scenario

I have a custom post type set up for products, along with a custom taxonomy (group of “categories”) to allow me to place them within a certain product range. On the product detail page I want to display a list of the other products within the same range.

Simple you would think? – It wasn’t.

The problem, and the solution

The normal category template functions don’t really work for this sort of thing – what you are dealing with here is what’s known in WordPress nomenclature as “terms”. This makes sense, because “categories” are only one part of WordPress’ system for dealing with content taxonomy, and custom taxonomies are essentially extending upon what’s already there in WordPress: “Categories” and “Tags”.

In the example below, the text “product-range” (bold in the code snippet) is the name I gave my custom taxonomy, so all you need to do is change that to the name you gave yours.

<nav>
<ul>
<?php
$terms = get_the_terms( $post->ID, 'product-range' );
if ( $terms && ! is_wp_error( $terms ) ) {

$ranges = array();

foreach ( $terms as $term ) 
{
$ranges[] = $term->name;
}

$theProductRange = join( ", ", $ranges );

$otherProducts = new WP_Query();
$otherProducts->query(array ('product-range' => $theProductRange, 'orderby' => 'title', 'order' => 'ASC' ));
?>
<?php while($otherProducts->have_posts()) : $otherProducts->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php } ?>
</ul>
</nav>

To explain what this is doing, let’s have a look at the important lines:

$terms = get_the_terms( $post->ID, 'product-range' );

This line uses WordPress’ get_the_terms() function to grab hold of all the taxonomy terms from product-range attached to the current custom post ($post->ID). The terms are then assigned to an array within a loop and joined at the end top create a comma-separated list.

Further down we then create a custom WordPress query:

$otherProducts = new WP_Query();
$otherProducts->query(array ('product-range' => $theProductRange, 'orderby' => 'title', 'order' => 'ASC' ));

This more or less says to WordPress:

Give me everything in the product-range taxonomy that is equal to our range, and order it ascending by its title

Then we just loop through the results:

<?php while($otherProducts->have_posts()) : $otherProducts->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>

You’re done! Hope this helps someone!