Skip to content

Instantly share code, notes, and snippets.

@santanup789
Created May 31, 2021 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santanup789/37a91de5e956169482508b6c33b8900d to your computer and use it in GitHub Desktop.
Save santanup789/37a91de5e956169482508b6c33b8900d to your computer and use it in GitHub Desktop.
Filter Custom Post Types by Taxonomy in WP Admin Dashboard
<?php
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 ( 'team' !== $post_type )
return;
// A list of custom taxonomy slugs to filter by
$taxonomies = array( 'department' );
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>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment