WordPress has a handy
get_terms() function that retrives a list of all the terms for a taxonomy – this is great if you are, for example, building a
<select> box for filtering a custom post type listing page. But there’s one big problem, if you use this on a shared taxonomy, it will show all terms even if they aren’t used on the particular post type you are dealing with. There is a
hide_empty argument that you can pass to
get_terms, but this only excludes terms that aren’t used for the default “post” post type.
What to do about it
Facing this today, I ended up with this little snippet that utilises a
$wpbd query along with
get_terms to achieve what we want:
- First it uses a nested select query to get the IDs for all posts in our custom post type, this is then immediately utilised by the outer select query to grab a list of term IDs from the term_relationships table
- Then this list of IDs is passed into
- Finally it’s output to build the select box
You’ll also notice in there it is being cached as a transient for 4 hours. Depending on the nature of your site and server you might not need this, or may need to adjust the duration.
The key parts to modify if you want to utilise this is
post_type='cpt' on line 8 and
'taxonomy' => 'country' on line 9. These set the custom post type you want to retrive terms for, and the name of your taxonomy respectively.