This is a powerful little snippet to allow filtering your post or custom post type by a specific taxonomy term in the WordPress admin.
In my use case I had a custom post type for ‘wp_hooks’. I then had a custom taxonomy called ‘categories’.
My first thought was to use sortable columns, but that would still require scrolling and possibly paging to get the right people.
I tried a few things and ended up with this nice snippet…
The only thing you need to change is your post type and your taxonomy name.
Add the following code to active theme’s functions.php
file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | /** * function to add filter by category in backend */ add_action('restrict_manage_posts', 'dcs_filter_post_type_by_taxonomy'); function dcs_filter_post_type_by_taxonomy() { global $typenow; $post_type = 'wp_hooks'; // change to your post type $taxonomy = 'categories'; // change to your taxonomy if ($typenow == $post_type) { $selected = isset($_GET[$taxonomy]) ? $_GET[$taxonomy] : ''; $info_taxonomy = get_taxonomy($taxonomy); wp_dropdown_categories(array( 'show_option_all' => __("Show All {$info_taxonomy->label}"), 'taxonomy' => $taxonomy, 'name' => $taxonomy, 'orderby' => 'name', 'selected' => $selected, 'show_count' => true, 'hide_empty' => false, )); }; } /** * Filter posts by taxonomy in admin * @author Mike Hemberger * @link http://thestizmedia.com/custom-post-type-filter-admin-custom-taxonomy/ */ add_filter('parse_query', 'dcs_convert_id_to_term_in_query'); function dcs_convert_id_to_term_in_query($query) { global $pagenow; $post_type = 'wp_hooks'; // change to your post type $taxonomy = 'categories'; // change to your taxonomy $q_vars = &$query->query_vars; if ( $pagenow == 'edit.php' && isset($q_vars['post_type']) && $q_vars['post_type'] == $post_type && isset($q_vars[$taxonomy]) && is_numeric($q_vars[$taxonomy]) && $q_vars[$taxonomy] != 0 ) { $term = get_term_by('id', $q_vars[$taxonomy], $taxonomy); $q_vars[$taxonomy] = $term->slug; } } |