I'm using the below code to list categories as hierarchical. On change of select options it is redirecting to the respective category pages. But it not showing the category as selected.Could any one help me on this please?
$terms = wp_dropdown_categories(array(
'taxonomy' => 'news-categories',
'hierarchical' => 1,
'show_option_none' => "CATEGORIES",
'option_none_value' => "",
'name' => 'news_cat_name',
'id' => 'cat_search',
'value_field' => 'slug',
'selected' => 1,
));
JavaScript:
$('#cat_search').change(function () {
if ($(this).val()) {
window.location = "<?php echo esc_url(home_url('/')); ?>news-categories/" + $(this).val();
}
});
I'm using the below code to list categories as hierarchical. On change of select options it is redirecting to the respective category pages. But it not showing the category as selected.Could any one help me on this please?
$terms = wp_dropdown_categories(array(
'taxonomy' => 'news-categories',
'hierarchical' => 1,
'show_option_none' => "CATEGORIES",
'option_none_value' => "",
'name' => 'news_cat_name',
'id' => 'cat_search',
'value_field' => 'slug',
'selected' => 1,
));
JavaScript:
$('#cat_search').change(function () {
if ($(this).val()) {
window.location = "<?php echo esc_url(home_url('/')); ?>news-categories/" + $(this).val();
}
});
Share
Improve this question
edited Jan 23, 2019 at 11:47
Krzysiek Dróżdż
25.6k9 gold badges53 silver badges74 bronze badges
asked Jan 23, 2019 at 10:10
Aparna MathewAparna Mathew
1651 gold badge2 silver badges9 bronze badges
1 Answer
Reset to default 3OK, so you've put this code on category archive, I assume, and the dropdown always shows the same category, right?
And it's exactly what it's supposed to do with current code. In this line:
'selected' => 1,
you decide, that item with value 1 is selected. Probably there is no such value (1 doesn't occur as term slug very often), so the first item is selected.
So how should that code really look like?
You should pass proper value as selected
param. If you're showing this dropdown on category archive page, then you can use get_queried_object()
function to obtain current category:
$current_category = get_queried_object();
$terms = wp_dropdown_categories(array(
'taxonomy' => 'news-categories',
'hierarchical' => 1,
'show_option_none' => "CATEGORIES",
'option_none_value' => "",
'name' => 'news_cat_name',
'id' => 'cat_search',
'value_field' => 'slug',
'selected' => $current_category->slug,
));