How to Filter WordPress Posts by Custom Taxonomy

      No Comments on How to Filter WordPress Posts by Custom Taxonomy

If you have lots of posts on your WordPress site, you have probably used the Category and/or date filters inside admin dashboard to filter WordPress posts. These filters are very much helpful  to display posts by a particular category or taxonomy. But, if you used any custom taxonomies or custom post types , then you have probably noticed that these options are not available for such taxonomies and post types. So here I’m going to show you how to add new filters with custom taxonomies to any post type you have registered on your WordPress site.

Add below code at the end of  functions.php file which is inside your theme folder, the only thing you need to change  in it is your post type and your taxonomy name. The rest will do automatically.

 

function techmagics_add_taxonomy_filters() {
global $typenow;

// an array of all the taxonomyies you want to display. Use the taxonomy name or slug
$taxonomies = array('publication');

// must set this to the post type you want the filter(s) displayed on
if( $typenow == 'post' ){

foreach ($taxonomies as $tax_slug) {
$tax_obj = get_taxonomy($tax_slug);
$tax_name = $tax_obj->labels->name;
$terms = get_terms($tax_slug);
if(count($terms) > 0) {
echo "<select name='$tax_slug' id='$tax_slug' class='postform'>";
echo "<option value=''>Show All $tax_name</option>";
foreach ($terms as $term) {
echo '<option value='. $term->slug, $_GET[$tax_slug] == $term->slug ? ' selected="selected"' : '','>' . $term->name .' (' . $term->count .')</option>';
}
echo "</select>";
}
}
}
}
add_action( 'restrict_manage_posts', 'techmagics_add_taxonomy_filters' );

Above code will create a “publication” taxonomy filter for the post type “post” , instead of ‘publication’  you can use your taxonomy name and for ‘post’ you can use your custom post type name. You can see a drop down menu with custom taxonomy in your dashboard, so you can now filter wordPress posts by custom taxonomy

Leave a Reply