Custom Taxonomy Category Dropdown

I needed to create a dropdown <select> menu for all of the categories in a custom taxonomy. WordPress has this cool built-in function called wp_dropdown_categories(), so I tried that with a custom taxonomy category dropdown using wp_dropdown_categories(‘taxonomy=custom-tax’), and it worked pretty well.

By playing around with the different $args and settings found here I was able to get it looking pretty spiffy. All of my categories were showing up, and the dropdown was functioning properly. The issue came when I clicked on a category.

WordPress sends you to the unpretty-fied link of /?cat=# which is not what I want if I’ve changed the permalink structure. So I did some digging and found this bit of code.

<?php

  $categories = get_categories('taxonomy=custom-tax');

  $select = "<select name='cat' id='cat' class='postform'>n";
  $select.= "<option value='-1'>Select category</option>n";

  foreach($categories as $category){
	if($category->count > 0){
		$select.= "<option value='".$category->slug."'>".$category->name."</option>";
	}
  }

  $select.= "</select>";

  echo $select;
?>

<script type="text/javascript"><!--
    var dropdown = document.getElementById("cat");
    function onCatChange() {
		if ( dropdown.options[dropdown.selectedIndex].value != -1 ) {
			location.href = "<?php echo home_url();?>/category/"+dropdown.options[dropdown.selectedIndex].value+"/";
		}
    }
    dropdown.onchange = onCatChange;
--></script>

Granted, that post was from 4 years ago, but I found no errors with the code using Theme Check.

Basically the code goes through all of the categories for you custom taxonomy, custom-tax in this case, and outputs the categories that have been created and have posts. You can adjust the $args by tweaking get_categories().

The JavaScript used finds your dropdown and depending on the category you select, it will send you to the proper slug when you click. This is adjustable by changing ‘category’ in the location.href to whatever you need it to go to.

I wanted to show all of a particular Custom Post Type with the category ‘Ohio’ from taxonomy ‘golf-course’ so I changed ‘category’ in location.href to ‘golf-course’. I then created taxonomy-golf-course.php so I could fine tune the output when it went to golf-course/ohio.

As with all things WordPress this is not the only way to get the desired display, but it’s what worked for me. If you’ve got a better way, let me know in the comments below.

Update: H├ędi Kairouannais pointed out that using multiple cat dropdowns presented some problems when duplicating the code. The easy answer is to make sure you are changing up the Javascript var for each new dropdown. The new code will look like the following:

Using Multiple Taxonomies

<div class="row">
<div class="col span_3"> <!-- TYPES DE PROJETS -->
<?php
  $categories = get_categories('taxonomy=type');
  $select = "<select name='cat' id='cat1' class='postform'>n";
  $select.= "<option value='-1'>Type ...</option>n";

  foreach($categories as $category){
        if($category->count > 0){
                $select.= "<option value='".$category->slug."'>".$category->name."</option>";
        }
  }

  $select.= "</select>";
  echo $select;
?>
<script type="text/javascript"><!--
    var cat1dropdown = document.getElementById("cat1");
    function onCat1Change() {
                if ( cat1dropdown.options[cat1dropdown.selectedIndex].value != -1 ) {
                        location.href = "<?php echo home_url();?>/type/"+cat1dropdown.options[cat1dropdown.selectedIndex].value+"/";
                }
    }
    cat1dropdown.onchange = onCat1Change;
--></script>
</div>

<div class="col span_3"> <!-- PHASE DE PROJETS -->
<?php
  $categories = get_categories('taxonomy=etat');
  $select = "<select name='cat' id='cat2' class='postform'>n";
  $select.= "<option value='-1'>Phase ...</option>n";

  foreach($categories as $category){
        if($category->count > 0){
                $select.= "<option value='".$category->slug."'>".$category->name."</option>";
        }
  }

  $select.= "</select>";
  echo $select;
?>
<script type="text/javascript"><!--
    var cat2dropdown = document.getElementById("cat2");
    function onCat2Change() {
                if ( cat2dropdown.options[cat2dropdown.selectedIndex].value != -1 ) {
                        location.href = "<?php echo home_url();?>/etat/"+cat2dropdown.options[cat2dropdown.selectedIndex].value+"/";
                }
    }
    cat2dropdown.onchange = onCat2Change;
--></script>
</div>
</div>

Update (cont.) Note how he has renamed the var in the second bit of script to ‘cat2dropdown’ and changed the ‘id’ of the select element to ‘cat2’? In this way you are making each bit of Javascript unique to that specific select element and preventing issues. For optimization, you should combine the scripts and toss them in your footer or a separate .js file, but this gets the point across and is confirmed to work properly.

If you’ve got more updates for the custom taxonomy category dropdown method, feel free to let me know and I’ll post it here.

Also, if you didn’t see the drag-and-drop xckd comic, you should. Click and drag, yo.

Subscribe
Notify of
guest
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Max
Max
8 years ago

Thanks John, I’ve been playing around with a solution for doing this over the last few hours and stumbled upon this post and it works perfectly for me!

Appreciate the post.

Derek
Derek
7 years ago

Geez dude, I have been researching how to do this for like 8 hours and I finally stumbled on this post! Plus 1

trackback

[…] have more insight, please feel free to share. Otherwise, check out some more WordPress functions: Custom Taxonomy Category Dropdowns or Custom Excerpt […]

Manish Gairola
Manish Gairola
6 years ago

Thanks for the code this is exactly what i needed ..i am able to see both the drop down however only one is routing to correct page and second one shows nothing routing to derfault 404 not found page.
i have created two custom taxonomies Department and Store also created two templates taxonomy-department.php and taxonomy-store.php … after putting your code and changing the taxonomies i am able to see both the dropdowns however only department dropdown is working but store once is routing to not found page.. please help.

robin
5 years ago

Hi, the above example works perfect, great for your to post it, the only extended query i have is, instead of default type i want it to say all, and on this i want to redirect to page with all posts? how to go about it?

John Hartley is a Director of Product Engineering at Beam Dental in Columbus, OH. With 5+ years of leadership experience he has worked in startups, agencies, and began his career as a freelance Front End Developer. Always looking to iterate, this blog is a place for him to share his knowledge as well as hone his craft, challenge assumptions, and build a strong base of leadership and management knowledge. Connect with him on LinkedIn

5
0
Would love your thoughts, please comment.x
()
x