Filter a second dropdown list when a value is chosen in the first one

You are going to want to use Ajax to do this to get the second drop-down to load after the first has been selected. I’m not sure about a couple things that you have going on up there, so I’m just going to code this out for you, you may have to change something here or there, I will complete it as well as possible. So the first thing to do is set up an ajax action. This should be setup within a plugin ideally. The is_admin() is used because when the Ajax request is sent from the page with your drop-down list, it will be running under admin. If it feels like we’re working backwards, it’s just a chicken egg thing. Which came first, the request or the handler… the handler of coarse, which is why I’m starting here.

<?php
if ( is_admin() ) {
    // We add 2 actions, the first is for logged in users, the second for guests.
    add_action( 'wp_ajax_dynamic_dropdown', 'dynamic_dropdown_func' );
    add_action( 'wp_ajax_nopriv_dynamic_dropdown', 'dynamic_dropdown_func' );
}

// This is the function that will handle your Ajax Request/Response
function dynamic_dropdown_func () {
    global $wpdb;
    if (isset($_POST['value'])) {
        $selected_option = $_POST['value'];
        // This will be your second dropdown here, this will be returned in an Ajax request
        $args = array(
            'show_option_none' => __( 'Pick Another One' ),
            'class' => 'dropper',
            'id' => 'dropper0',
            'orderby' => 'ID',
            'order' => 'ASC',
            'hide_empty' => 0,
            'hierarchical' => 1,
            'depth' => 1,
            // This is what will get us the children of first selected option
            'child_of' => (int)$selected_option,
            'echo' => 0,
            // Make sure you switch out this const for your tax
            'taxonomy' => MY_CUSTOM_TAX,
        );

        $my_second_dropdown = wp_dropdown_categories( $args );
        // If you want to do any preg_replace or str_replace, do it here before we do the ob_clean() below         
    }
    //ob_clean is to prevent errors, echos, anything that has outputted to this point in the Ajax WP instance that could ruin your return.
    ob_clean();
    return $my_second_dropdown;
    wp_die();
}

Ok, so now we are going to do the front end part of the code. This is the part that the user will see. When they trigger the Ajax Request, upon response the second dropdown should load. Normally, you would localize a JavaScript file with the variable for the ajax_url and any other PHP values that we need to use in our JS to send Ajax requests to WP. We are going to cheat a little and just print our script out to the page and we will get the same result. Just make sure that you print this script out at the end of the body ideally, or else you will have to add in a document ready function, it wouldn’t hurt anyways.

function my_frontend_javascript () {
    $ajax_url = admin_url( 'admin-ajax.php' );
    $javascript = "
        <script>
            var ajaxUrl = {$ajax_url},
            // Now lets grab our dropdowns
                dropdownArome   = jQuery('#arome0'),
                dropdownDropper = jQuery('#dropper0');

            if (dropdownArome.length && dropdownDropper.length) {
                // Good, our elements exist
                dropdownArome.on('change', function (e) {
                    var value = e.target.selectedOptions[0].value,
                        success,
                        data;
                    if (!!value) {
                        // Alright, lets send that value to our Ajax Script, note that the action is the same as the Ajax action hook we used earlier
                        data = {
                            'my_value' : value,
                            'action'   : 'dynamic_dropdown'
                        };
                        success = function ( response ) {
                            // This response will hold our <option>'s
                            dropdownDropper.html( response );
                        };
                        jQuery.post( ajaxUrl, data, success );
                    }
                });
            }
        </script>";
    return $javascript;
}

/** This is where we build our site/form/dropdowns */

$args = array(
    'show_option_none' => __( 'Pick One' ),
    'class' => 'arome',
    'id' => 'arome0"',
    'orderby' => 'ID',
    'order' => 'ASC',
    'hide_empty' => 0,
    'hierarchical' => 1,
    'depth' => 1,
    'echo' => 0,
    // Make sure you switch out this const
    'taxonomy' => MY_CUSTOM_TAX,
);

$my_first_dropdown = wp_dropdown_categories( $args );

// Alright, so now we print out the 2 dropdowns, then the JavaScript from function we wrote above
echo $my_first_dropdown;
echo '<br /><div id="dropper0-container"></div><br />';
echo my_frontend_javascript();

/** That Should be it! Like I said, you will have to tweak some options to fit your site and your implementation. */

So that is how you would do what you are trying to do in what I guess could be one of the simplest ways. I say simplest because we really did no validation, nonce, we pretty much assumed that everything went well. I would suggest reading up on Ajax in WP, even if you know some, it can never hurt to know more. I hope this code works well for you with some tweaking.

http://codex.wordpress.org/AJAX_in_Plugins

http://www.smashingmagazine.com/2011/10/18/how-to-use-ajax-in-wordpress/

Leave a Comment