Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
@andretti1977

This comment has been minimized.

Copy link

andretti1977 commented Mar 15, 2019

Don't you get term count equal to zero any time?

@koskinenaa

This comment has been minimized.

Copy link
Owner Author

koskinenaa commented Apr 10, 2019

@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
You can’t perform that action at this time.