Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.