wp_dropdown_categories and custom taxonomy + custom post type
-
22-04-2021 - |
Question
I have created custom post type called "case study"(with slug case-study), with support of custom taxonomy which is called "theme".
What i am trying to achieve? Simple dropdown, with redirect to specific taxonomy term page on option select.
The code:
<form
id="category-select"
class="category-select"
action="<?php bloginfo('url'); ?>" method="get">
<?php
$args = array(
'show_option_all' => __( 'Choose theme', 'l-p' ),
'hide_empty' => 0,
'echo' => 0,
'show_count' => 0,
'taxonomy' => 'theme',
);
$select = wp_dropdown_categories( $args );
$replace = "<select$1 onchange='return this.form.submit()'>";
$select = preg_replace( '#<select([^>]*)>#', $replace, $select );
echo $select;
?>
<noscript><input type="submit" value="View" /></noscript>
</form>
Thing is, i'm getting dropdown with proper list of taxonomy terms, but when clicking on specifc option(from dropdown) it redirects me to weird pages/urls instead of actual taxonomy template page.
- I have tried saving direct links in wp settings.
- Taxonomy have proper template called taxonomy-theme.php
- The same dropdown works properly for default blog posts.
- CPT and taxonomy is created via CPT UI(i'm not really fond of it, but well, it was "required") - the support for taxonomy/cpt is checked in options.
- The slug for custom taxonomy is "theme".
- The slug for custom post type is "case-study".
- The taxonomy terms pages are present, it's just that dropdown redirects incorrectly.
Any help would be much appreciated.
Solution
You can get your code to work the expected way by adding the following three arguments to your $args
array which you pass to wp_dropdown_categories()
:
name
— theselect
name as in<select name="<here>">
, and you should set it totheme
which is your custom taxonomy slug.value_field
— the value of the<option>
's in thatselect
dropdown, e.g.<option value="<here>">
.And you should set the arg to
slug
so that when the form is submitted (or when a term is selected), the browser would go tohttps://example.com/?theme=term-slug-here
and then WordPress redirects the browser to the correct term permalink if (and it's commonly) enabled.selected
— the selected option which is a term in the customtheme
taxonomy and because the form's destination is the term archive page, and that a term slug was specified (see the sample URL above), then set this arg toget_query_var( 'theme' )
to get the slug of the term being queried on the page.
So try with:
$args = array(
'show_option_all' => __( 'Choose theme', 'l-p' ),
'hide_empty' => 0,
'echo' => 0,
'show_count' => 0,
'taxonomy' => 'theme',
// Add these three args:
'name' => 'theme', // same as the "taxonomy" above
'value_field' => 'slug', // use the term slug
'selected' => get_query_var( 'theme' ),
);