wp_dropdown_categories – Pass category id to javascript

Just to pretense this. I have a page with a dropdown list which shows my custom taxonomy. When an item is select, I want the page to load the_content from the posts in that taxonomy.

So far, I’ve got the_content loading from everything, however I seem to be struggling with the dropdown.

Read More

On this page template, I have a dropdown using wp_dropdown_categories:

                 <?php 
                 $args = array(
                    'taxonomy' => 'company',
                    'hide_empty'         => 0,
                    'orderby'            => 'NAME', 
                    'class' => 'chosen-select'
                 );

                 wp_dropdown_categories( $args ); ?> 

This lists all the categories from my custom taxonomy and they are listed in HTML as:

<option class="level-0" value="7">Customer ABC</option>

I’ve also got some JQuery which at the moment, alerts me to when the dropdown is changed:

    $(".chosen-select").change(function () {
        alert("Hello");
    });

What I want to do is to reload the page so that my PHP can grab the category id from the custom taxonomy and load it into my loop. The PHP is the easy part, however it’s been a while since I’ve done any Javascript and I seem to be having a bit of a mental blockage.

I know I need to use

    $(".chosen-select").change(function(value) {
        window.location('?catid=' + value);
    });

to reload the page, however I cannot for the life of me figure out how to grab the category ID from the dropdown in WordPress and pass it to my function. Any pointers?

Related posts

Leave a Reply

1 comment

  1. What you need is to grab the value of the current element. You can use $(this) to select the current element, and then .val() to grab its value.

    See the modified code below:

    $(".chosen-select").change(function(value) {
        window.location = window.location.origin + window.location.pathname + '?catid=' + $(this).val();
    });
    

    See jQuery val and the jQuery Object.

    Update: Modified the code above to utilize the origin and pathname to grab a query-free url, to avoid duplicates and conflicts.