in Design & Dev & Themes & Tutorials

Displaying custom post types with the same custom taxonomy value

Recently I was working on a WordPress theme where I wanted to be able to display a list of posts from a custom post type (specifically a milestones post type) that shared the same custom taxonomy value (in this case, a project ID) as the current post.

Not being a programmer, I struggled for far too long to write a buggy and obese query that would never do. After extensive searching, I came across Automattician Michael Fields’ solution on WP Questions. Since it wasn’t the easiest thing to find, I’m sharing it here with comments for easy adaptation to your purposes:

<?php
/* $projects is a variable you can change to something more suitable throughout */
/* project_id is the name of the custom taxonomy */
$projects = get_the_terms( get_the_ID(), 'project_id' );
if ( ! is_wp_error( $projects ) && is_array( $projects ) ) {
$term = array_shift( $projects );
/* $milestones is a variable you can change to something more suitable throughout */
$milestones = null;
if ( isset( $term->slug ) && isset( $term->taxonomy ) ) {
$milestones = get_posts( array(
'term' => $term->slug,
'taxonomy' => $term->taxonomy,
// Enter your custom post type slug below
'post_type' => 'pplan_milestones',
'orderby' => 'menu_order',
'order' => 'asc',
'numberposts' => '0', // 0 will show all results
'post_status' => 'publish',
) );
}
// Loop over all posts of the CPT and display them
if ( $milestones ) {
$_post = $post;
print '<ul>';
foreach ( (array) $milestones as $post ) {
setup_postdata( $post );
/* Write whatever output you want here. This just returns a simple unordered list. */
the_title( '<li><a href="' . esc_url( get_permalink() ) . '">', '</a></li>>' );
}
print '<ul>';
$post = $_post;
}
}
?>

Comments (3)

  1. Nice! One question, though… Is it possible to change the order of the list? I want the oldest to be first (I know, it's weird, but I have my reasons), and I'm not sure how to go about this. I tried changing the "'order' => 'asc'" to "'order' => 'desc'" but to no success.

  2. Just wanted to say thanks, Josh! I've been looking for this exact setup for some time now, but was only finding methods for specific/manually defined taxonomies rather than dynamically pulling the post's tax. Thanks!