Create a dropdown of custom taxonomies in WordPress (the easy way)

So you’ve been busy taking advantage of custom post type functionalities in WordPress since mid 2010. And of course you’re using custom taxonomies too, right? Of course you are.

If you’re a theme or plugin developer you may have ran across the need to populate a dropdown list of your custom taxonomies. Essentially there are two different (easy) ways to accomplish this. One you always hear about and the other you don’t.

Method #1

Since WP 2.1 the wp_dropdown_categories function has been around but in WP 3.0 the taxonomy argument was introduced. So just calling this function and using the taxonomy argument is probably the absolute easiest way to populate a dropdown list of your custom taxonomies.

This method is great if you need the output of your dropdown values to be the category ID. Because this is the HTML that will be generated:


However, let’s say you want your option value output to be the taxonomy’s slug instead of the ID. Well, that’s impossible to achieve using the wp_dropdown_categories function.

Peering into the WordPress core we see that this function is using a walker class called Walker_CategoryDropdown. This walker is designed to output only the ID as the value for each dropdown item. There is not an argument in the function to control value output.

Method #2

That’s where Method #2 comes in. We’ll have to write our own custom function that will generate the dropdown so we can output each option value as a slug:

function fjarrett_custom_taxonomy_dropdown( $taxonomy ) {
	$terms = get_terms( $taxonomy );
	if ( $terms ) {
		printf( '' );
	}
}

So, now that we’ve got a cool custom function, we can call anywhere in our code like so:

Expansions on Method #2

If you’re a coding rockstar you can take Method #2 even further by making room for more parameters. This will give you even more control and make it function more like wp_dropdown_categories does:

function fjarrett_custom_taxonomy_dropdown( $taxonomy, $orderby = 'date', $order = 'DESC', $limit = '-1', $name, $show_option_all = null, $show_option_none = null ) {
	$args = array(
		'orderby' => $orderby,
		'order' => $order,
		'number' => $limit,
	);
	$terms = get_terms( $taxonomy, $args );
	$name = ( $name ) ? $name : $taxonomy;
	if ( $terms ) {
		printf( '' );
	}
}

Then call it in your code like so:

Conclusion

As you can see, WordPress has done a fabulous job of making room for you and I to do pretty much whatever we want.

To reference all available arguments and parameters, please see:
http://codex.wordpress.org/Function_Reference/wp_dropdown_categories
http://codex.wordpress.org/Function_Reference/get_terms

Was this code helpful to you? Let me know in the comments!

39 thoughts on “Create a dropdown of custom taxonomies in WordPress (the easy way)

  1. Tim

    This works great for listing custom taxonomies but I’m having trouble getting it to submit once a selection is made.

    Any help would be greatly appreciated.

    Thanks!

    Reply
  2. Frankie Post author

    Tim, sounds like this could be an issue with the form you’re using to wrap this dropdown element. Send me a link and I’ll check it out.

    //Frankie

    Reply
    1. Tim

      Hi Frankie.

      Thanks for the tutorial.

      I think I’m having the same problem as the other Tim – the dropdown is populated OK but it doesn’t submit when an item is selected.

      This is the code that I’m trying to use – a combination of your tutorial and the wp_dropdown_categories() tutorial I found in the Codex:

      <form action="/" method="get">
      

      Can you point me in the right direction?

      Thanks,

      Tim

      Reply
      1. Frankie Post author

        Hi, Tim. I’d be happy to help. Ok, it depends on what function you want to perform.

        Are you using it to do a search on the front-end?

        Or are you using it in the WP Admin?

        //Frankie

      2. noe ruiz

        Hey Frankie, I’m having the same issue. I’m trying to perform a simple query on a custom front page using the dropdown without a submit button. Thanks,

        Noe

    2. siudek

      And? Any good ideas? I’m also doing something wrong with this – previously I had used different solutions, but this seems to be clear and simple – and I like this kind of solution very much. ;]

      BTW – many thanks for sharing the experience on the net. It sure helps in many many projects and saves tons of time. Thank you again for your time.

      /siudek

      Reply
  3. Caleb M

    Wow, this post was very helpful! I can’t believe how long it took me to figure out a dropdown for custom taxonomies…

    Someone was asking about how to get the form to submit, so you may want to complete this tutorial by adding the complete function that wordpress devs should add to their functions.php

    For me this was:

    function custom_taxonomy_dropdown($taxonomy, $name, $show_option_all) { ?>
    	<form action="" method="get">
    	 $orderby,
    		'order' => $order,
    		'number' => $limit
    	);
    	$terms = get_terms($taxonomy, $args);
    	echo '';
    	if($show_option_all) echo ''.$show_option_all.'';
    	if($show_option_none) echo ''.$show_option_none.'';
    	foreach ($terms as $term) {
    		echo 'slug.'">'.$term->name.'';
    	}
    	echo ''; 
    	?>
    <?php }
    
    Reply
    1. noe ruiz

      Hi Caleb,

      I tried adjusting this to my functions page, is there a chance the formatting is off? I get errors when using this function. It’s also strange because the form tag isn’t closing.

      Reply
  4. Nathan

    Apparently you’re the only person who cares to post a simple, useful tutorial. THANK YOU! I’ve been testing different tutorials until my eyes were red. Your code did the trick without any complications!

    Reply
  5. Michael Weaver

    This is working excellently. I am trying to add a ‘All’ option to the select, to filter to all taxonomies.

    function custom_taxonomy_dropdown($taxonomy) {
    	$terms = get_terms($taxonomy);
    	echo '';
    		echo 'All';
    	foreach ($terms as $term) {
    		echo 'slug.'">'.$term->name.'';
    	}
    	echo '';
    }
    

    I’m guessing value="0" isn’t correct. Any ideas?

    Reply
  6. Michael Weaver

    Thanks bud,

    just had a look at the second method, and it seemed to work perfectly until I tried the select all option, which in effect does work, it shows all ‘posts’. Im using this script for a custom post type archive page, attempting to show a dropdown menu of the custom taxonomies.

    Here is the code thats in my archive page…

    and here is the function…

    function custom_taxonomy_dropdown($taxonomy, $orderby, $order, $limit, $name, $show_option_all) {
    	$args = array(
    		'orderby' => $orderby,
    		'order' => $order,
    		'number' => $limit
    	);
    	$terms = get_terms($taxonomy, $args);
    	echo '';
    	if($show_option_all) echo ''.$show_option_all.'';
    	if($show_option_none) echo ''.$show_option_none.'';
    	foreach ($terms as $term) {
    		echo 'slug.'">'.$term->name.'';
    	}
    	echo '';
    }
    

    The value="0" shows all the posts, but none of the custom post pages, all of the others work perfectly. Any ideas?

    On a side note, someone asked about it submitting the form without a button, just add onchange="this.form.submit();" to the select element, works perfectly :D

    Reply
    1. Nathan

      Using some of the comments on this page, and some of Frankie’s original tutorial, I’ve put together what I think most people are interested in, a tutorial on how to implement this as a dropdown without a submit button. It doesn’t seem like code posts into the comments very easily / well here so I’ll just link to it and Frankie can add the code to my comment if he’d prefer.

      http://clicknathan.com/web-design/wp_dropdown_categories-for-custom-taxonomies/

      Reply
      1. Frankie Jarrett Post author

        Hey Nate, I’ve updated my code above to properly escape the variables being outputted in the HTML. I suggest you update the code on your blog as well. Thanks again!

  7. Dimitri

    Hi Frankie,

    is there a way to display more than one select box, each one for a different taxonomy in order to filter posts by multiple criteria..

    Thank you

    Dimitri

    Reply
  8. Kahil

    How can this be applied to pages? In the codex there is an example of how to get a dropdown for categories and have it go to the selection without having a submit button. But I can’t get the same method to work for the page dropdown code provided in the codex. Any ideas?

    Reply
    1. Frankie Jarrett Post author

      Hi Kahil, Perhaps I will take a look at that issue and write a separate blog post. This post was intended for working with custom taxonomies only.

      Reply
      1. Kahil

        Thank you… been trying to figure that out for days now without any success. Please feel free to email me a possible solution if you’d like.

        Thanks

  9. Bryan Young

    There is a simpler way to do this without rewriting the entire wp_dropdown_categories() function.

    wp_dropdown_categories() accepts an argument called ‘walker’ which can be a custom instance of the Walker_CategoryDropdown class.

    So to make your dropdown output slugs as values instead of ids you could do something like this:

    In your theme’s functions.php:

    class Walker_SlugValueCategoryDropdown extends Walker_CategoryDropdown {
    
            function start_el( &$output, $category, $depth, $args, $id = 0 ) {
                    $pad = str_repeat(' ', $depth * 3);
    
                    $cat_name = apply_filters('list_cats', $category->name, $category);
    
                    /** Only the following line is changed from the original class **/
                    $output .= "\tslug."\"";
    
                    if ( $category->term_id == $args['selected'] )
                            $output .= ' selected="selected"';
                    $output .= '>';
                    $output .= $pad.$cat_name;
                    if ( $args['show_count'] )
                            $output .= '  ('. $category->count .')';
                    $output .= "\n";
            }
    }
    
    And in your template file:
    
    $dropdown_args = array(
            'taxonomy' => 'your-custom-taxonomy',
            'walker'      => new Walker_SlugValueCategoryDropdown);
    
    wp_dropdown_categories( $dropdown_args );
    
    Reply
    1. shelly

      Hey Bryan – I was trying to use your solution here, but there seems to be some syntax errors, and I’m not sure where you’re putting the last $output .= sprintf(‘slug); bit. The solution Frankie has up works great, except like Michael I need to select all option enabled and am using this on custom post types, not blog posts.

      I think your solution will work, if I can get it to … work? :-)

      Reply
  10. Hernandez

    Hi everybody, really nice post i was try to find something like that. ;-) Thanks

    I have this problem, I’m working with wp and woocommerce and i have to populate the drodown menu like here (the old website) search website is dinamyc, help to the clients how to find a product, they have something like 10.000 products wines…
    any idea how to risolve this dropdown search?

    any help ?
    thankssss a lot

    Reply
    1. Frankie Jarrett Post author

      Hi Pete, Since a dropdown of custom taxonomies could have many different uses, this tutorial is simply about how to create the dropdown, not how to make a form.

      Reply
  11. Daniel Martines

    Hi guys! I have a taxonomy that I share beetween 2 post types.
    I need to create a dropdown that shows the taxonomy from just one post type. Is this possible?

    Thanks!

    Reply
  12. Hane

    I’m using method #2 and would like to know how I can make my drop down hierarchical. I added hierarchical => true to the $arg but its not working. Any help would be very much appreciated.

    Thanks
    Hanè

    Reply
  13. Matías

    Hi! First at all, thanks for your tutorial.

    I can’t get it working. I’m tryng to retrieve categories from WP e-commerce plugin (taxonomy = wpsc_product_category) and nothing is shown.

    Any ideas?

    Thanks in advance.

    ps: sorry for my english.

    Reply
  14. Musab

    How can I take advantage of that on my search results.

    For example, to as this menu next to the search box and filter results by the selected taxonomy category.

    Reply
  15. John

    I have been struggling to create a custom real estate search for my website for weeks now. The function I’m trying to build is not complicated. I’m very familiar with WP and can follow directions very well. If any of you is willing to help I could pay you for an hour of work ($30) to help me figure this thing out. Please shoot me an email..

    Reply
  16. Damien

    Hey!

    First of all, great article! I have been looking for something like this for a long time!

    I have implemented the “Expansions on Method #2″ version of the code, which is working, except for the Search All option. I have added the code exactly as in the article and when I run my search for All items, the url does show a value of 0 for my taxonomies, however, I am presented with a page saying no results found.

    The page I am testing this on is http://adoptapet.ie/pets/farms/
    Am I missing something here, ha?

    Cheers

    Damien

    Reply

Leave a Reply