AJAX列出Wordpress精选中的类别和子类别

时间:2018-12-11 17:13:46

标签: php jquery wordpress

Footer.php-用于Ajax调用

 <script>
    jQuery(document).ready(function($) {
                $('#main_cat').change(function(){
                        var $mainCat=$('#main_cat').val();

                        // call ajax
                         $("#sub_cat").empty();
                            $.ajax({
                                url:"/wp-admin/admin-ajax.php",
                                type:'POST',
                                                            data:'action=my_special_action&main_catid=' + $mainCat,

                                 success:function(results)
                                     {
                                    //  alert(results);
                    $("#sub_cat").removeAttr("disabled");
                    $("#sub_cat").append(results);
                                            }
                                       });
                              }
                                        );
    })( jQuery );
    </script>

在function.php中-我用于回调

<?php
add_action('wp_ajax_my_special_action', 'my_action_callback');
//add_action('wp_ajax_nopriv_my_special_action', 'my_action_callback');

function implement_ajax() {
if(isset($_POST['main_catid']))
            {
            $categories=  get_categories('child_of='.$_POST['main_catid'].'&hide_empty=0');
              foreach ($categories as $cat) {
                $option .= '<option value="'.$cat->term_id.'">';
                $option .= $cat->cat_name;
                $option .= ' ('.$cat->category_count.')';
                $option .= '</option>';
              }

              echo '<option value="-1" selected="selected">Select</option>'.$option;
            die();
            } // end if
}
add_action('wp_ajax_my_special_ajax_call', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_ajax_call', 'implement_ajax');//for users that are not logged in.

在page.php中-我用它来显示结果

<?php
                        wp_dropdown_categories('taxonomy=listing-category&show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat&orderby=name&order=ASC');
                    ?>





<select name="sub_cat" id="sub_cat" disabled="disabled"></select>

我使用了这段代码,但是没有用。我在哪里做错了? 谁能帮我修复它? 请帮助我。我需要修复它。

0 个答案:

没有答案