Add a custom taxonomy dropdown filter to the WordPress Media Library

If you like my WordPress work, check out my new plugin, Bylines. Thanks!

The Media Library is one of WordPress’ most-used features. Because it comprises thousands of lines of JavaScript, it’s also one of the least-customized. If you know where to poke, it’s relatively straightforward to add a custom taxonomy dropdown filter to the toolbar:

2016-01-25 at 1.17 PM.png

For the code snippet that follows, here’s a high-level overview of how the dropdown filter is added for the Collection taxonomy:

  1. We extend wp.media.view.AttachmentFilters to create our own attachment filter, which is assigned to the MediaLibraryTaxonomyFilter variable.
  2. With our filter variable defined, we extend and override wp.media.view.AttachmentsBrowser to inject the rendering of our attachment filter. Because WordPress doesn’t have JavaScript actions and filters, customizing core JavaScript requires this pattern of extend and override. Remember: extend and override. Also remember to call a copy of the original function (where the other filters are added) if you’re looking for the same behavior as subclassing.
  3. We use wp_localize_script() to make our custom taxonomy’s terms available for use on the frontend.

This code snippet is all you need to add a custom taxonomy dropdown filter. There are annotations to indicate where you need to make changes: