Add a Custom Taxonomy Filter to WordPress Custom Post Type

/Add a Custom Taxonomy Filter to WordPress Custom Post Type

Recently, a client needed to be able to filter their custom post type posts list by a given taxonomy, making it easier to find what they were looking for.   Fortunately with WordPress this isn’t difficult.

For the example below, the client was a restaurant who had a custom post type named dish, and a taxonomy associated with it named dish-type.

All that was required was to add the following code to your theme, or child-theme’s functions.php file.

add_action( 'restrict_manage_posts', 'my_restrict_manage_posts' );

function my_restrict_manage_posts() {
  global $typenow;
  $taxonomy = 'dish-type';
  if( $typenow != "page" && $typenow != "post" ){
    $filters = array($taxonomy);
    foreach ($filters as $tax_slug) {
      $tax_obj = get_taxonomy($tax_slug);
      $tax_name = $tax_obj->labels->name;
      $terms = get_terms($tax_slug);
      echo "<select id="$tax_slug" class="postform" name="$tax_slug">";
      echo "
<option value="">Show All $tax_name</option>";
      foreach ($terms as $term) { echo '
<option selected="selected" value=". $term-&gt;slug, $_GET[$tax_slug] == $term-&gt;slug ? ">' . $term-&gt;name .' (' . $term-&gt;count .')</option>'; }
      echo "

Pay particular attention to the $taxonomy = ‘dish-type’ line.  This is the taxonomy slug, and all you’ll need to implement a custom filter.

The results of the above code are as follows – a nice filter allowing the user to easily find what they are looking for by refining by a custom taxonomy.

2018-11-07T01:02:32+00:00October 6th, 2018|Web Programming, WordPress Snippets|0 Comments

About the Author:

Warren Chandler is a freelance web programmer and web developer, based in Frinton on Sea, Essex. Warren specialises in web programming, web design, corporate identity, copy writing, SEO, logo and print media for home, work, and mobile platforms.

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.