0

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();
    }
});

1 Answer 1

3

OK, 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,
));
1
  • Glad it is working :) Thank you for the detailed explanation. Commented Jan 23, 2019 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.