Search code examples
ajaxwordpressdropdowncustom-post-type

Show second dependent dropdown without reloading the page


I am trying to build a "price calculator" on my website, to show repair prices for various smartphones. I already managed to create to dropdowns, the second one only showing after the first one is selected. After making a choice in the first dropdown, the page reloads and then shows the second one. I would like to achieve the same without reloading the page. This is the code I have so far:

<form method="POST" action="">
                    <div>
                        <?php
                            $args = array(
                                'hierarchical' => 1,
                                'depth' => 1,
                                'orderby' => 'name',
                                'echo' => 0,
                                'taxonomy' => 'marke',
                                // this leads to variable name $_POST['marke']
                                'name' => 'marke-sel'
                            );
                            if( ! isset($_POST['marke-sel']) ):
                                $args['show_option_none'] = 'Hersteller ausw&auml;hlen';
                            else:
                                $args['selected'] = $_POST['marke-sel'];
                            endif;
                            $marke = wp_dropdown_categories( $args );
                            // this enables the buttonless js possibility
                            $marke = preg_replace("#<select([^>]*)>#", "<select$1 onchange='return this.form.submit()'>", $marke);
                            echo $marke;
                        ?>
                        <noscript>
                            <div>
                                <input type="submit" value="marke" />
                            </div>
                        </noscript>
                    </div>
                </form>
                
                <?php
                    if( isset($_POST['marke-sel']) && $_POST['marke-sel'] ):
                ?>
                
                <form method="POST" action="<? bloginfo('url'); ?>">
                    <input type="hidden" name="marke" value="<?php echo $_POST['marke-sel'] ?>">
                    <div>
                    <?php
                        $the_query = new WP_Query( array(
                            'post_type' => 'reparaturpreise',
                            'tax_query' => array(
                                array (
                                    'taxonomy' => 'marke',
                                    'field' => 'id',
                                    'terms' => $_POST['marke-sel'],
                                )
                            ),
                        ) );

                        if ( $the_query->have_posts() ) :
                    ?>
                    <div class="form-option parent-field-wrapper">
                        <label for=""></label>
                        <select name='modell' id='modell' onchange='document.location=this.value'>
                            <option value="">Modell ausw&auml;hlen</option>
                            <?php while ( $the_query->have_posts() ) :
                                $the_query->the_post();
                            ?>
                            <option value="<?php the_permalink();?>"><?php the_title(); ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <?php endif;
                    wp_reset_postdata();
                    
                    $modell = preg_replace("#<select([^>]*)>#", "<select$1 onchange='this.form.submit()'>", $modell);
                                echo $modell;
                            ?>
                            <noscript>
                                <div>
                                    <input type="submit" value="modell" />
                                </div>
                            </noscript>
                        </div>
                    </form>
                <?php endif; ?>
                
                <?php
                if( isset($_POST['marke-sel']) && $_POST['modell']  ):
                    $args = array( 
                        'post_type' => 'reparaturpreise',
                        'cat' => $_POST['marke-sel'],
                        'posts_per_page' => 1 
                    ); 
                $loop = new WP_Query( $args ); 
                while ( $loop->have_posts() ) : $loop->the_post(); 
                    the_title();
                    echo '<div class="entry-content">'; 
                        the_content(); 
                    echo '</div>'; 
                endwhile;
                endif;
                ?>

Solution

  • I finally managed to get it working using this code from here: http://webprow.com/blog/dynamic-dependent-dropdown-categories-posts/

    For anyone else looking for a similar solution, this is the code you need to insert in functions.php:

    if ( ! class_exists( 'frontendAjaxDropdown' ) ):
        class frontendAjaxDropdown {
            
            function __construct() {
                add_shortcode( 'ajax-dropdown', array($this, 'init_shortocde') );
                add_action( 'wp_ajax_get_subcat', array($this, 'getSubCat') );
                add_action('wp_ajax_nopriv_get_subcat', array($this, 'getSubCat') );
            }
            
            function init_shortocde()
            
            { ?>
            
            <div class="ajax-dropdown">
                <?php
                $args = array(
                    'name' => 'main_cat',
                    'id'=> 'main_cat',
                    'selected' => -1,
                    'hierarchical' => '1',
                    'depth' => 1,
                    'show_option_none' => 'ENTER PLACEHOLDER FOR TAXONOMY HERE',
                    'option_none_value' => '',
                    'hide_empty' => 0,
                    'taxonomy' => 'ENTER YOUR TAXONOMY HERE'
                );
                wp_dropdown_categories($args);
                ?>
    
                <script type="text/javascript">
                    (function($){
                        $("#main_cat").change(function(){
                            $("#sub_cat").empty();
                            $.ajax({
                                type: "post",
                                url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                                data: { action: 'get_subcat', cat_id: $("#main_cat option:selected").val() },
                                beforeSend: function() {$("#loading").animate({ opacity: 1 });},
                                success: function(data) {
                                    $("#loading").animate({ opacity: 0 });
                                    $("#sub_cat").append(data);
                                }
                            });
                        });
                        $("select option[value='']").attr('disabled',"disabled"); 
                        $("select option[value='']").attr('selected',"selected"); 
                    })(jQuery);
                </script>
                <div id="loading" style="opacity: 0;">wird geladen...</div>
                    <div id="sub_cat"></div>
                    </div>
                </div>
                
            <?php }
     
            function getSubCat() { 
                $cat_id = $_POST['cat_id'];
                $args=array(
                    'post_type' => 'ENTER YOUR CPT HERE',
                    'tax_query' => array(
                        array (
                            'taxonomy' => 'ENTER YOUR TAXONOMY HERE',
                            'field' => 'id',
                            'terms' => $cat_id
                        )
                    ),
                );
        
                $my_query = null;
                $my_query = new WP_Query($args);
    
                if( $my_query->have_posts() ) { ?>
                    <select name="menu[]" onchange='document.location=this.value'>
                        <option value="" disabled selected>ENTER PLACEHOLDER FOR CPT HERE</option>
                        <?php
                            while ($my_query->have_posts()) : $my_query->the_post(); ?>
                                <option value="<?php the_permalink();?>" ><?php the_title(); ?> </option>
                        <?php 
                            endwhile;
                            wp_die();
                        ?>
                    </select>
                <?php 
                    wp_reset_query();
                    die();
                ?>  <?php }
            }
        }
    endif;
    new frontendAjaxDropdown();
    

    After that, you can place the dropdowns using this shortcode:

    <?php echo do_shortcode("[ajax-dropdown]"); ?>