Monthly Archives: September 2011

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!