I have a taxonomy of type
and a taxonomy of category
.
How can I return a list of every type
term of posts in a single category
?
I know I can do this:
// Final array of all types:
$allTypesFromThisCategory = [];
if (have_posts()) : while (have_posts()) : the_post();
$types = wp_get_post_terms( $post->ID, 'type' );
foreach($types as $type){
// Pseudo code:
if( ! in_array($type, $allTypesFromThisCategory) ){
// Add the type to the array
$allTypesFromThisCategory[] = $type;
}
}
endwhile; endif;
print_r($allTypesFromThisCategory);
But there are a couple of problems with this.
- There are about 1,000 posts, so it will be really slow.
- Assuming
posts_per_page
isn’t -1 this query won’t always reflect all thetypes
of all the posts, just the ones on the current page.
I’d like to write something like
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM ...", OBJECT );
Where the ...
represents:
- Use the current
category
taxonomy - Find all the
posts
with thatcategory
taxonomy ID - Select all
types
taxonomy of thoseposts
… but the problem is I can’t / am terrible at writing joins and raw SQL.