Filter Admin Lists by Any Taxonomy
Adds a dropdown filter for every taxonomy attached to a post type, such as tags or custom taxonomies on a portfolio.
Opens WPIDE on
Code
// Taxonomies that should not get a dropdown (WordPress already shows one for post categories).
$wpide_tax_filter_skip = array( 'category', 'post_format' );
add_action( 'restrict_manage_posts', function ( $post_type ) use ( $wpide_tax_filter_skip ) {
foreach ( get_object_taxonomies( $post_type, 'objects' ) as $taxonomy ) {
if ( ! $taxonomy->show_ui || ! $taxonomy->query_var || in_array( $taxonomy->name, $wpide_tax_filter_skip, true ) ) {
continue;
}
$selected = isset( $_GET[ $taxonomy->query_var ] ) ? sanitize_title( wp_unslash( $_GET[ $taxonomy->query_var ] ) ) : '';
wp_dropdown_categories( array(
'taxonomy' => $taxonomy->name,
'name' => $taxonomy->query_var,
'value_field' => 'slug',
'selected' => $selected,
'show_option_all' => $taxonomy->labels->all_items,
'hierarchical' => $taxonomy->hierarchical,
'hide_empty' => false,
'hide_if_empty' => true,
'show_count' => true,
) );
}
} );
// The "All" option submits 0; drop it so the list is not filtered by a term called "0".
add_filter( 'request', function ( $vars ) {
if ( ! is_admin() ) {
return $vars;
}
foreach ( get_taxonomies( array( 'show_ui' => true ), 'objects' ) as $taxonomy ) {
if ( $taxonomy->query_var && isset( $vars[ $taxonomy->query_var ] ) && '0' === (string) $vars[ $taxonomy->query_var ] ) {
unset( $vars[ $taxonomy->query_var ] );
}
}
return $vars;
} );
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.