Create a WordPress Custom Taxonomy Dropdown without a Submit Button
If you’re creating your own custom taxonomies for WordPress, you may want to provide a list of the terms in those within a dropdown, where users can then select one of the terms and be taken to that page. This is theoretically possible just using wp_dropdown_categories
, however in practice it’s a bit more difficult.
The problem is, if you’re using the code provided on the Codex page for that function and Pretty Permalinks, you’ll get a 404 when the form submits, because by default the function assigns the ID of a given term to its equivalent option in the select field (when what we need is the slug). I’ve cobbled together a variety of code to get you up and running.
First, the wp_dropdown_categories
Code for your Theme
Paste the code below wherever you’d like to display the dropdown menu:
<form method="get" action="/">
<fieldset>
<?php $args = array(
'show_option_all' => 'Choose one...',
'taxonomy' => 'YOUR-TAXONOMY-SLUG',
'walker' => new my_Walker_CategoryDropdown
);
wp_dropdown_categories( $args ); ?>
<script type="text/javascript"><!--
var dropdown = document.getElementById("cat");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value != '0' ) {
location.href = "<?php echo get_option('home');
?>/?YOUR-TAXONOMY-SLUG="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
--></script>
</fieldset>
</form>
Remember to replace both instances of YOUR-TAXONOMY-SLUG above with the actual slug for the taxonomy you want to show. The key ingredient here which separates this from the default code provided in the Codex (which works with Categories), is the walker object in our $args
array. Using the code provided on this WordPress support page, we can add the following to our functions.php file to work the necessary magic.
class my_Walker_CategoryDropdown extends Walker_CategoryDropdown {
function start_el(&$output, $category, $depth, $args) {
$pad = str_repeat(' ', $depth * 3);
$cat_name = apply_filters('list_cats', $category->name, $category);
$output .= "\t<option class=\"level-$depth\" value=\"".$category->slug."\"";
if ( $category->term_id == $args['selected'] )
$output .= ' selected="selected"';
$output .= '>';
$output .= $pad.$cat_name;
if ( $args['show_count'] )
$output .= ' ('. $category->count .')';
if ( $args['show_last_update'] ) {
$format = 'Y-m-d';
$output .= ' ' . gmdate($format, $category->last_update_timestamp);
}
$output .= "</option>\n";
}
}
There’s a lot going on there, but essentially we’re changing the value of each select item from echoing the ID to echoing the slug for that term instead.
Enjoy!
Up Next: Optimize Your WordPress Website for Facebook with OpenGraph