Skip to content

Instantly share code, notes, and snippets.

@neilgee
Last active November 7, 2021 20:27
Show Gist options
  • Save neilgee/71ec2fa5ff6b1d427900 to your computer and use it in GitHub Desktop.
Save neilgee/71ec2fa5ff6b1d427900 to your computer and use it in GitHub Desktop.
Custom Taxonomy Dropdown Search
<?php
//http://clicknathan.com/web-design/wordpress-custom-taxonomy-dropdown-without-a-submit-button/
//This goes function.php
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";
}
}
//This goes where you want the form input to appear - change to your taxonomy slug in 2 locations
<form method="get" action="/">
<fieldset>
<?php $args = array(
'show_option_all' => 'Choose one...',
'taxonomy' => 'YOUR-TAXONOMY-SLUG',
'orderby' => 'name',
'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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment