Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save koskinenaa/86fd3acd75959e9aa0635ce00934e26c to your computer and use it in GitHub Desktop.
Save koskinenaa/86fd3acd75959e9aa0635ce00934e26c to your computer and use it in GitHub Desktop.
Add filtering by custom taxonomies to a post type. Note when registering the custom taxonomies 'query_var' should not be set to false. If so, this function won't work,
/**
* Add taxonomy filtering to custom post types
*
* Original example for one post type, https://generatewp.com/filtering-posts-by-taxonomies-in-the-dashboard/
*
*/
function filter_cpt_by_taxonomies( $post_type, $which ) {
// Affected post types
$post_types = array(
'my_post_type',
'my_another_post_type'
);
// Apply this only on a specific post type
if ( ! in_array( $post_type, $post_types ) ) {
return;
}
// Get associated taxonomies names
$taxonomies = get_object_taxonomies( $post_type, 'object' );
// Bail early
if ( ! $taxonomies ) {
return;
}
// Loop taxonomies
foreach ( $taxonomies as $taxonomy ) {
// Retrieve taxonomy terms
$terms = get_terms( $taxonomy->name );
// Bail early
if ( ! $terms || is_wp_error( $terms ) ) {
continue;
}
// Display filter HTML
echo "<select name='{$taxonomy->name}' id='{$taxonomy->name}' class='postform'>";
echo '<option value="">' . sprintf( esc_html__( 'Show All %s', 'textdomain' ), $taxonomy->label ) . '</option>';
foreach ( $terms as $term ) {
printf(
'<option value="%1$s" %2$s>%3$s (%4$s)</option>',
$term->slug,
( ( isset( $_GET[$taxonomy->name] ) && ( $_GET[$taxonomy->name] == $term->slug ) ) ? ' selected="selected"' : '' ),
$term->name,
$term->count
);
}
echo '</select>';
}
}
add_action( 'restrict_manage_posts', 'filter_cpt_by_taxonomies' , 10, 2);
@koskinenaa
Copy link
Author

@andretti1977 That's actually a good question. I didn't think about that when writing the gist, but I now added couple of checks to the code. I also realized the foreach loop was totally unnecessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment