Category (Taxonomy) Dropdown Filtered By Post Type

Screen Shot 2016-02-19 at 9.20.28 PM

While working on a large custom content management solution for a client I was building templates for multiple post types all sharing a common taxonomy. Most of these templates needed a dropdown to filter the results by the common taxonomy, in this case a taxonomy named “department.”

Should be fairly straight-forward, right? WordPress does offer a great function for creating taxonomy dropdowns called wp_dropdown_categories, which works with custom taxonomies as well as categories.

However, it will return all taxonomies with any posts. If you have multiple post types, you could very easily get a list of taxonomies with posts, but not the post type you want for the template – as was my issue.

Luckily, we can filter the SQL query used in the get_terms function, which is called by wp_dropdown_cateogies.

The above utilizes the term_clauses filter, and hunts for the post_type argument. The beauty of this is that we’re extending the functionality of the get_terms function directly.

This means we can use wp_dropdown_categories and simply pass our new post_type argument. Furthermore, the fallback here is the built-in function, which is a double bonus. I love the extend-ability of WordPress!

Here’s the basic usage, now that we have the filter above:

That said, I built a custom function to wrap the wp_dropdown_categories, so I could grab the current query var and add a wrapper element.

Here are some useful resources if you’re going down this rabbit hole:


One response to “Category (Taxonomy) Dropdown Filtered By Post Type”

  1. Patrick Avatar

    Ah very cool. I was wondering how to do something like this. Yet another thing to add to my list to try out. Thanks very much.

Leave a Reply

Your email address will not be published. Required fields are marked *