Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have a code in my functions.php to display 3-level taxonomy dropdown:

            $brand_taxonomy = 'county';
            $taxonomy_name = 'Vietovės pasirinkimas';

            add_action('add_meta_boxes', 'my_custom_metabox');
            function my_custom_metabox() {
            add_meta_box('custom-taxonomy-dropdown','Vietovės pasirinkimas','taxonomy_dropdowns_box','post','side','high');
            }

            function taxonomy_dropdowns_box( $post ) {
            global $brand_taxonomy, $taxonomy_name;
            wp_nonce_field('custom-dropdown', 'dropdown-nonce');
            $terms = get_terms( $brand_taxonomy, 'hide_empty=0');
            if ( is_a( $terms, 'WP_Error' ) ) {
                $terms = array();
            }

            $object_terms = wp_get_object_terms( $post->ID, $brand_taxonomy, array('fields'=>'ids'));
            if ( is_a( $object_terms, 'WP_Error' ) ) {
                $object_terms = array();
            }

            // you can move the below java script to admin_head
            ?>
            <script type="text/javascript">
                jQuery(document).ready(function() {
                        jQuery('#custom_apskritis_options').change(function() {
                            var custom_apskritis = jQuery('#custom_apskritis_options').val();
                            if ( custom_apskritis == '0') {
                                jQuery('#custom_savivaldybe_options').html('');
                                jQuery('#savivaldybe_container').css('display', 'none');
                                jQuery('#miestas_container').css('display', 'none');
                            } else {
                                jQuery('#ctd-custom-taxonomy-terms-loading').css('display', 'inline');
                                jQuery('#savivaldybe_container').css('display', 'none');
                                var data = {
                                    'action':'get_apskrities_savivaldybes',
                                    'custom_apskritis':custom_apskritis,
                                    'dropdown-nonce': jQuery('#dropdown-nonce').val()
                                };
                                jQuery.post(ajaxurl, data, function(response){
                                    jQuery('#custom_savivaldybe_options').html(response);
                                    jQuery('#ctd-custom-taxonomy-terms-loading').css('display', 'none');
                                    jQuery('#savivaldybe_container').css('display', 'inline');
                                });
                            }
                        });
                        jQuery('#custom_savivaldybe_options').change(function() {
                            var custom_savivaldybes = jQuery('#custom_savivaldybe_options').val();
                            if ( custom_savivaldybes == '0') {
                                jQuery('#custom_miestas_options').html('');
                                jQuery('#miestas_container').css('display', 'none');
                            } else {
                                jQuery('#ctd-custom-taxonomy-terms-loading2').css('display', 'inline');
                                jQuery('#miestas_container').css('display', 'none');
                                var data = {
                                    'action':'get_savivaldybes_miestai',
                                    'custom_savivaldybes':custom_savivaldybes,
                                    'dropdown-nonce': jQuery('#dropdown-nonce').val()
                                };
                                jQuery.post(ajaxurl, data, function(response){
                                    jQuery('#custom_miestas_options').html(response);
                                    jQuery('#ctd-custom-taxonomy-terms-loading2').css('display', 'none');
                                    jQuery('#miestas_container').css('display', 'inline');
                                });
                            }
                        });
                });
            </script>
            <?php
            echo "Apskritis:";
            echo "<select id='custom_apskritis_options' name='custom_apskritis[]'>";
            echo "<option value='0'>Nepasirinkta</option>";
            foreach ( $terms as $term ) {
                if ( $term->parent == 0) {
                    if ( in_array($term->term_id, $object_terms) ) {
                        $parent_id = $term->term_id;
                        echo "<option value='{$term->term_id}' selected='selected'>{$term->name}</option>";
                    } else {
                        echo "<option value='{$term->term_id}'>{$term->name}</option>";
                    }
                }
            }
            echo "</select><br />";
            echo "<div id='ctd-custom-taxonomy-terms-loading' style='display:none;'>Atrenkamos...</div>";
            echo "<div id='savivaldybe_container'";
            if ( !isset( $parent_id)) echo " style='display: none;'";
            echo ">";
            echo "Savivaldybė:";
            echo "<select id='custom_savivaldybe_options' name='custom_apskritis[]'>";
            if ( isset( $parent_id)) {
                $savivaldybes = get_terms( $brand_taxonomy, 'hide_empty=0&parent='.$parent_id);
                foreach ( $savivaldybes as $savivaldybe ) {
                     if ( in_array($savivaldybe->term_id, $object_terms) ) {
                        $parent_id_savivaldybe = $savivaldybe->term_id;
                        echo "<option value='{$savivaldybe->term_id}' selected='selected'>{$savivaldybe->name}</option>";
                    } else {
                        echo "<option value='{$savivaldybe->term_id}'>{$savivaldybe->name}</option>";
                    }
                }
            }
            echo "</select><br />";
            echo "</div>";

            echo "<div id='ctd-custom-taxonomy-terms-loading2' style='display:none;'>Atrenkami...</div>";
            echo "<div id='miestas_container'";
            if ( !isset( $parent_id_savivaldybe)) echo " style='display: none;'";
            echo ">";
            echo "Miestas:";
            echo "<select id='custom_miestas_options' name='custom_apskritis[]'>";
            if ( isset( $parent_id_savivaldybe)) {
                $miestas = get_terms( $brand_taxonomy, 'hide_empty=0&parent='.$parent_id_savivaldybe);
                foreach ( $miestas as $miesta ) {
                     if ( in_array($miesta->term_id, $object_terms) ) {
                        echo "<option value='{$miesta->term_id}' selected='selected'>{$miesta->name}</option>";
                    } else {
                        echo "<option value='{$miesta->term_id}'>{$miesta->name}</option>";
                    }
                }
            }
            echo "</select>";
            echo "</div>";  
            }

            add_action('save_post','save_my_custom_taxonomy');
            function save_my_custom_taxonomy( $post_id ) {
            global $brand_taxonomy, $taxonomy_name;
            if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
                return;

            if ( !wp_verify_nonce($_POST['dropdown-nonce'],'custom-dropdown'))
                return;

            $brands = array_map('intval', $_POST['custom_apskritis']);
            wp_set_object_terms($post_id, $brands, $brand_taxonomy);
            }

            add_action('wp_ajax_get_apskrities_savivaldybes', 'get_apskrities_savivaldybes');
            function get_apskrities_savivaldybes() {
            global $brand_taxonomy, $taxonomy_name;
            check_ajax_referer('custom-dropdown', 'dropdown-nonce');
            if (isset($_POST['custom_apskritis'])) {
                $models = get_terms( $brand_taxonomy, 'hide_empty=0&parent='.$_POST['custom_apskritis']);
                echo "<option value='0'>Pasirinkti vieną</option>";
                foreach ($models as $model) {
                    echo "<option value='{$model->term_id}'>{$model->name}</option>";
                }
            }
            die();
            }

            add_action('wp_ajax_get_savivaldybes_miestai', 'get_savivaldybes_miestai');
            function get_savivaldybes_miestai() {
            global $brand_taxonomy, $taxonomy_name;
            check_ajax_referer('custom-dropdown', 'dropdown-nonce');
            if (isset($_POST['custom_savivaldybes'])) {
                $miestai = get_terms( $brand_taxonomy, 'hide_empty=0&parent='.$_POST['custom_savivaldybes']);
                echo "<option value='0'>Pasirinkti vieną</option>";
                foreach ($miestai as $miesta) {
                    echo "<option value='{$miesta->term_id}'>{$miesta->name}</option>";
                }
            }
            die();
            }

How I can make this code work in frontend (in searchform). Thanks in advance!

share|improve this question
2  
as a sidenote, this is bad UX, you would be better off choosing a different UI pattern as this will not fail gracefully if a piece of JS fails to load, or errors out, or the user needs assistive tech. I recommend you use taxonomy archives and follow the drill down pattern, it's more powerful, easier to implement, more foolproof, and easier to use, e.g. look at ecommerce sites that let you drill down through categories to specific categories eg. Kitchens -> electrical -> kettles –  Tom J Nowell Apr 30 '13 at 10:47

1 Answer 1

After spending many hours using google I managed to make 3-level hierarchical taxonomy dropdown with ajax. Here is my code:

searchform.php

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" ></script>
    <script type="text/javascript">
        $(function(){
            $('#apskritis').change(function(){
                var $apskritisSlug=$('#apskritis').val();
                // call ajax
                 $("#savivaldybe").empty();
                 $("#miestas_kaimas").empty();
                    $.ajax({
                        url:"/wp-admin/admin-ajax.php",
                        type:'POST',
                        data:'action=get_savivaldybes&apskritis_slug=' + $apskritisSlug,
                        success:function(results) {
                          //alert(results);
                            $("#savivaldybe").removeAttr("disabled");
                            $("#savivaldybe").append(results);
                        }
                    });
                }
            );
            $('#savivaldybe').change(function(){
                var $savivaldybeSlug=$('#savivaldybe').val();
                // call ajax
                $("#miestas_kaimas").empty();
                    $.ajax({
                        url:"/wp-admin/admin-ajax.php",
                        type:'POST',
                        data:'action=get_miestai&savivaldybes_slug=' + $savivaldybeSlug,
                        success:function(results) {
                          //alert(results);
                            $("#miestas_kaimas").removeAttr("disabled");
                            $("#miestas_kaimas").append(results);
                        }
                    });
                }
            );      
        });
    </script>       

    <?php
        function get_terms_dropdown_county($taxonomies, $args){

            $taxonomies = array('county'); // CHANGE ME
            $args = array(
                    'order'=>'ASC',
                    'hide_empty'=>false,
                    'parent'=> 0
                    );

            $myterms = get_terms($taxonomies, $args);
            $optionname = "county";
            echo "<div class='input_wrap div_".$optionname."'>";
            echo "<select id='apskritis' class='select_".$optionname."' name='".$optionname."'>'";
            echo "<option value='0'>Nepasirinkta</option>";

            foreach($myterms as $term){
                if ( $term->parent == 0) {
                    echo "<option value='{$term->slug}'>{$term->name}</option>";
                } 
            }
            echo "</select>";
            echo "</div>";
            echo "<div class='input_wrap div_".$optionname."'>";
            echo '<select id="savivaldybe" name="county" disabled="disabled"></select>';
            echo '<select id="miestas_kaimas" name="county" disabled="disabled"></select>';
        }

        echo get_terms_dropdown_county($taxonomies, $args);
    ?>  

functions.php code:

            function savivaldybes_implement_ajax() {
                if(isset($_POST['apskritis_slug'])) {

                    $parent_slug = $_POST['apskritis_slug'];
                    $get_parent_id = get_term_by('slug', $parent_slug, 'county');
                    $parent_id = $get_parent_id->term_id;

                    $savivaldybes = get_terms( 'county', 'hide_empty=0&parent='.$parent_id);
                        foreach ($savivaldybes as $sav) {
                            $option .= '<option value="'.$sav->slug.'">';
                            $option .= $sav->name;
                            $option .= '</option>';
                        }
                    echo '<option value="0" selected="selected">Nenurodyta</option>'.$option;
                    die();
                } // end if
            }
            add_action('wp_ajax_get_savivaldybes', 'savivaldybes_implement_ajax');
            add_action('wp_ajax_nopriv_get_savivaldybes', 'savivaldybes_implement_ajax');//for users that are not logged in.

            function miestas_kaimas_implement_ajax() {
                if(isset($_POST['savivaldybes_slug'])) {

                    $sav_parent_slug = $_POST['savivaldybes_slug'];
                    $sav_get_parent_id = get_term_by('slug', $sav_parent_slug, 'county');
                    $sav_parent_id = $sav_get_parent_id->term_id;

                    $miestas_kaimas = get_terms( 'county', 'hide_empty=0&parent='.$sav_parent_id);
                        foreach ($miestas_kaimas as $kaimas) {
                            $option .= '<option value="'.$kaimas->slug.'">';
                            $option .= $kaimas->name;
                            $option .= '</option>';
                        }
                    echo '<option value="0" selected="selected">Nenurodyta</option>'.$option;
                    die();
                } // end if
            }
            add_action('wp_ajax_get_miestai', 'miestas_kaimas_implement_ajax');
            add_action('wp_ajax_nopriv_get_miestai', 'miestas_kaimas_implement_ajax');//for users that are not logged in.

I don't know is this code right but it is working form me :)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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