(Moderator’s note: The original title was “drop down taxonomy”)
I want to add a drop-down box filled
with my custom taxonomies, so when
someone selects any value, it
redirects to corresponding page. I
tried out this code, which worked
<?php wp_dropdown_categories( array(
'taxonomy' => 'name of taxonomy' ) );
?>
The problem is I want a the page to
redirect without the user needing to
press any buttons. How can I do this?
this question was resolved but i want to modify further, i want to add a shortcode, so that i can also call drop-down-list into my post, i tried this but not working
add_shortcode('drop','the_taxonomy_dropdown');
but when i call this in my post [drop="location"]
its not working,
whats the problem?
Hi @ntechi:
Here’s a function I wrote which I named the_taxonomy_dropdown()
to give you what I think you are looking for.
function the_taxonomy_dropdown($taxonomy) {
$id = "{$taxonomy}-dropdown";
$js =<<<SCRIPT
<script type="text/javascript">
jQuery(document).ready(function($){
$("select#{$id}").change(function(){
window.location.href = $(this).val();
});
});
</script>
SCRIPT;
echo $js;
$terms = get_terms($taxonomy);
echo "<select name=\"{$id}\" id=\"{$id}\">";
foreach($terms as $term) {
echo '<option value="';
echo get_term_link(intval($term->term_id),$taxonomy);
echo '">' . "{$term->name}</option>";
}
echo "</select>";
}
You can put the_taxonomy_dropdown()
in your theme’s functions.php
file and call it from one of your theme’s template files like so:
<?php the_taxonomy_dropdown('name of taxonomy'); ?>
Notice I didn’t use wp_dropdown_categories()
because it sets the <option>
‘s values to term_id
instead of the term’s permalink. You need the permalink in order to set the window.location.href
on the client end. Had we used wp_dropdown_categories()
it have would added more complexity; it would have required issuing an HTTP GET request with term_id
to a page on the server that would then redirect to the term’s permalink. But it’s much easier to just build the HTML <select>
ourselves as I did (and it’s more peformant, since it doesn’t take an extra HTTP request.)
Of course, be sure to remember wp_enqueue_script()
jQuery in an 'init'
hook, also in your theme’s functions.php
file:
add_action('init','jquery_init');
function jquery_init() {
wp_enqueue_script('jquery');
}