Filter Custom Post Types by Taxonomy in WP Admin Dashbaord

Filter CPTs by a linked custom Taxonomy in the WP Admin Dashboard is possible with restrict_manage_posts.

Filter Cpt By Custom Taxonomy

In the screenshot there is a CPT list of posts, with a dropdown menu of a linked custom taxonomy terms which are filterable via the filter button next to it.

The code goes in functions.php

<?php // <~ don't add me in
add_action( 'restrict_manage_posts', 'filter_backend_by_taxonomies' , 99, 2);
/* Filter CPT via Custom Taxonomy */
/* https://generatewp.com/filtering-posts-by-taxonomies-in-the-dashboard/ */
function filter_backend_by_taxonomies( $post_type, $which ) {
// Apply this to a specific CPT
if ( 'light' !== $post_type )
return;
// A list of custom taxonomy slugs to filter by
$taxonomies = array( 'light_category' );
foreach ( $taxonomies as $taxonomy_slug ) {
// Retrieve taxonomy data
$taxonomy_obj = get_taxonomy( $taxonomy_slug );
$taxonomy_name = $taxonomy_obj->labels->name;
// Retrieve taxonomy terms
$terms = get_terms( $taxonomy_slug );
// Display filter HTML
echo "<select name='{$taxonomy_slug}' id='{$taxonomy_slug}' class='postform'>";
echo '<option value="">' . sprintf( esc_html__( 'Show All %s', 'text_domain' ), $taxonomy_name ) . '</option>';
foreach ( $terms as $term ) {
printf(
'<option value="%1$s" %2$s>%3$s (%4$s)</option>',
$term->slug,
( ( isset( $_GET[$taxonomy_slug] ) && ( $_GET[$taxonomy_slug] == $term->slug ) ) ? ' selected="selected"' : '' ),
$term->name,
$term->count
);
}
echo '</select>';
}
}
view raw functions.php hosted with ❤ by GitHub

So change to your CPT – example uses ‘light’ and Custom Taxonomy – example uses ‘light_category’.

The action has a late priority of ’99’ so it ends up closer to the filter button in the dashboard.

2 Comments

  1. Max on June 17, 2019 at 3:55 pm

    how do we add another post type to the function, can I just add another post type to the if condition followed by a comma ? such as ” if ( ‘light’, ‘show’ !== $post_type) and adding the taxonomy here as well ( $taxonomies = array( ‘light_category’, ‘show_category’ );

  2. ROSEMARY on May 21, 2019 at 4:05 am

    it doesnt work. We created the custom taxonomies with CPT UI

Leave a Comment