Dynamic dropdown list in wordpress

I want to generate State – District dropdown multi select dropdowns in WordPress.. According to the selections of States, Districts has to be loaded..

Please suggest me if there is available any plugin..

Related posts

Leave a Reply

3 comments

  1. I’ve recently written a blog post about this: http://bdwm.be/how-to-create-dynamically-populated-cascading-dropdown-lists-for-contact-form-7/. This example is with cars, but I applied to your case it would look something like this:

    You could start with a CSV file containing all the states/districts, like this:

    State,District
    Alabama,"District 1"
    Alabame,"District 2"
    ....
    

    save it as states_districts.csv and place it somewhere on your server. (In this example I placed it in the wp-content/uploads folder)

    Then using the contact form 7 plugin create 2 select fields:

    [select states]
    [select districts]
    

    Next, create some javascript in your page’s footer, that will perform an AJAX call

    <script>
    (function($) {
    
        // create references to the dropdown fields for later use.
    
        var $states_dd = $('[name="states"]');
        var $districts_dd = $('[name="districts"]'); 
    
        // run the populate_fields function, and additionally run it every time a value changes
    
        populate_fields();
        $('select').change(function() {
            populate_fields();
        });
    
        function populate_fields() {
    
            var data = {
    
                // action needs to match the action hook part after wp_ajax_nopriv_ and wp_ajax_ in the server side script.
    
                'action' : 'cf7_populate_values', 
    
                // pass all the currently selected values to the server side script.
    
                'state' : $states_dd.val(),
                'district' : $districts_dd.val(),
            };
    
            // call the server side script, and on completion, update all dropdown lists with the received values.
    
            $.post('<?php echo admin_url( 'admin-ajax.php' ) ?>', data, function(response) {
                all_values = response;
    
                $states_dd.html('').append($('<option>').text(' -- choose state -- '));
                $districts_dd.html('').append($('<option>').text(' -- choose district  -- '));
    
                $.each(all_values.states, function() {
                    $option = $("<option>").text(this).val(this);
                    if (all_values.current_state == this) {
                        $option.attr('selected','selected');
                    }
                    $states_dd.append($option);
                });
                $.each(all_values.districts, function() {
                    $option = $("<option>").text(this).val(this);
                    if (all_values.current_district == this) {
                        $option.attr('selected','selected');
                    }
                    $districts_dd.append($option);
                });
            },'json');
        }
    
    })( jQuery );
    </script>
    

    Finish up by creating your server side function that will read in the CSV file and return the correct values to the javascript:

    add this to functions.php:

    function ajax_cf7_populate_values() {
    
        // read the CSV file in the $states_districts array
    
        $states_districts = array();
        $uploads_folder = wp_upload_dir()['basedir'];
        $file = fopen($uploads_folder.'states_districts.csv', 'r');
    
        $firstline = true;
        while (($line = fgetcsv($file)) !== FALSE) {
            if ($firstline) {
                $firstline = false;
                continue;
            }
            $states_districts[$line[0]][$line[1]][] = $line[2];
    
        }
        fclose($file);
    
            // setup the initial array that will be returned to the the client side script as a JSON object.
    
        $return_array = array(
                'states' => array_keys($states_districts),
                'districts' => array(),
                'current_state' => false,
                'current_district' => false
            );
    
            // collect the posted values from the submitted form
    
        $state= key_exists('state', $_POST) ? $_POST['state'] : false;
        $district = key_exists('district', $_POST) ? $_POST['district'] : false;
    
            // populate the $return_array with the necessary values
    
        if ($state) {
            $return_array['current_state'] = $state;
            $return_array['districts'] = array_keys($states_districts[$state]);
            if ($district) {
                $return_array['current_district'] = $district;
            }
    
            // encode the $return_array as a JSON object and echo it
    
            echo json_encode($return_array);
            wp_die();
    
    }
    
    // These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
    // if a script is POSTing the action : 'cf7_populate_values'
    
    add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
    add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
    
  2. I want to share a fix for anyone that is trying to use this code.
    There is a mistake in line:

    $file = fopen($uploads_folder.'states_districts.csv', 'r');
    

    it should be

    $file = fopen($uploads_folder.'/states_districts.csv', 'r');
    
  3. Where do you wish to use the drop downs ? In plugins or in themes or just in page ?

    This can be done using Ajax calls. In general, you should register a Ajax call handler in plugin/theme and add your dynamic dropdowns in your page.

    http://codex.wordpress.org/AJAX_in_Plugins

    jQuery is embedded with WordPress, check this section on how to create dynamic dropdown

    http://www.jqueryscript.net/demo/Dynamic-jQuery-Cascading-Dropdown-Lists-Plugin/