不幸的是,给出的答案不起作用。我只看了jQuery部分,但问题出在functions过滤器中,我在最初的帖子中没有包括它。然而,你确实把我推向了我需要的方向,所以谢谢你!
问题是,我总是从AJAX函数得到响应。空响应不会清除之前的响应,因此我的内容抽屉在打开后永远不会关闭。我最终做的是通过创建一个空的模板部件来修改返回结果的函数。这样,空的select输入将返回一个空div。
以下是完整的代码,以防您想知道:
功能。PHP============
add_action(\'wp_ajax_repfilter\', \'repfilter\'); // wp_ajax_{ACTION HERE}
add_action(\'wp_ajax_nopriv_repfilter\', \'repfilter\');
function repfilter() {
$catSlug = $_POST[\'category\'];
$ajaxreps = new WP_Query([
\'post_type\' => \'sales_reps\',
\'post_status\' => \'publish\',
\'posts_per_page\' => -1,
\'tax_query\' => array(
array (
\'taxonomy\' => \'State\',
\'field\' => \'slug\',
\'terms\' => $catSlug,
)
),
\'orderby\' => \'title\',
\'order\' => \'ASC\',
]);
$response = \'\';
if($catSlug == \'\') { // This was the key! If the dropdown selection is empty, return this empty template file.
$response .= get_template_part(\'template_parts/null-item\');
} else {
if($ajaxreps->have_posts()) {
while($ajaxreps->have_posts()) : $ajaxreps->the_post();
$response .= get_template_part(\'template_parts/rep-item\');
endwhile;
} else {
$response = \'Sorry. There are no sales reps in your area.\';
}
}
echo $response;
exit;
}
还有jQuery==================
$(function(){
var event_change = $(\'#event-change\');
$( ".select" ).selectCF({
change: function(){
var value = $(this).val();
var text = $(this).children(\'option:selected\').html();
$.ajax({
url: ajaxurl,
type: \'POST\',
dataType: \'html\',
data: {
action: \'repfilter\',
category: $(this).children(\'option:selected\').data(\'slug\'),
},
success:function(res){
$(\'#response\').html(res);
if($(".repItem").length == 0) { // And this little piece checks if the results have a div present, which it would not if the empty template file was returned, and removes the "open" class.
$(\'#response\').removeClass(\'open\');
} else {
$(\'#response\').addClass(\'open\');
}
}
});
}
});
})
这样就解决了问题。请参见代码示例中的注释。我相信这不是一个非常优雅的解决方案,但它确实奏效了。