我正在尝试使用 AJAX 更改 WP_Query 中的 orderby 和 order 参数,但我无法确定为什么我的代码不起作用
I am trying to use AJAX to change the orderby and order arguments in a WP_Query, but I can't determine why my code won't work
所以我已经为此工作了几个小时。其中大约 6 个没有中断,我不明白为什么这不起作用。
所以我有这个表格:
<div id="wp-ajax-filter-search" class="full">
<form action="" method="get">
<div class="flex filters-grid">
<div id="#sortBy" class="flex filters-dropdown">
<p class="filters-title">
Sort By
</p>
<div class="filters-options">
<input class="wp-drop-filter-item" type="radio" id="alphabetically" value="title" name="sort_filter">
<label for="alphabetically">
Alphabetically
</label>
<input class="wp-drop-filter-item" type="radio" id="datenew2old" value="ASC" name="sort_filter">
<label for="datenew2old">
Date Added (New to Old)
</label>
<input class="wp-drop-filter-item" type="radio" id="dateold2new" value="DESC" name="sort_filter">
<label for="dateold2new">
Date Added (Old to New)
</label>
</div>
</div>
<div id="#countries" class="flex filters-dropdown">
<p class="filters-title">
Country
</p>
<?php
// set up a new query for each category, pulling in related posts.
$destinations = new WP_Query(
array(
'showposts' => -1,
'post_type' => 'destinations',
'post_status' => 'publish',
'order_by' => 'title',
'order' => 'ASC'
)
);
if ($destinations->have_posts()):
?>
<div class="filters-options">
<input class="wp-drop-filter-item <?php echo $country_slug ?>" type="radio" id="any" value="any" name="country_filter">
<label for="any">
Any
</label>
<?php while ($destinations->have_posts()) : $destinations->the_post();
global $post;
$post_slug = $post->post_name;?>
<input class="wp-drop-filter-item country-option" type="radio" id="<?php echo $post_slug ?>" value="<?php echo $post->ID ?>" name="country_filter" >
<label for="<?php echo $post_slug; ?>">
<?php echo get_the_title(); ?>
</label>
<?php endwhile; ?>
<?php
// Reset things, for good measure
$destinations = null;
wp_reset_postdata();
?>
</div>
<?php endif; ?>
</div>
<div id="#regions" class="flex filters-dropdown">
<p class="filters-title">
Region <span class="extra">(Choose Country First)</span>
</p>
<?php
// set up a new query for each category, pulling in related posts.
$regions = new WP_Query(
array(
'showposts' => -1,
'post_type' => 'regions',
'post_status' => 'publish',
'order_by' => 'title',
'order' => 'ASC'
)
);
if ($regions->have_posts()):
?>
<div class="filters-options">
<input class="wp-drop-filter-item" type="radio" id="any-region" value="any" name="region_filter">
<label class="region-option" for="any-region">
Any
</label>
<?php while ($regions->have_posts()) : $regions->the_post();
global $post;
$post_slug = $post->post_name;
$country = get_field( "country", $post );
$country_slug = get_post_field( 'post_name', $country ); ?>
<input class="wp-drop-filter-item" type="radio" id="<?php echo $post_slug ?>" value="<?php echo $post->ID ?>" name="region_filter">
<label class="region-option <?php echo $country_slug ?>" for="<?php echo $post_slug; ?>">
<?php echo get_the_title(); ?>
</label>
<?php endwhile; ?>
<?php
// Reset things, for good measure
$regions = null;
wp_reset_postdata();
?>
</div>
<?php endif; ?>
</div>
</div>
</form>
<ul id="ajax_filter_search_results" class="destinations grid"></ul>
</div>
每当您更改其中一个单选按钮时,都会使用以下 JS 代码触发 AJAX:
var wpmafs = $("#wp-ajax-filter-search");
var wpmafsForm = wpmafs.find("form");
$(".wp-drop-filter-item").on("change",function(e){
e.preventDefault();
var sort_filter = $("input[name='sort_filter']:checked").val();
var country_filter = $("input[name='country_filter']:checked").val();
var region_filter = $("input[name='region_filter']:checked").val();
var data = {
action : "wp_ajax_filter_search",
sort_filter : sort_filter,
country_filter : country_filter,
region_filter : region_filter
};
console.log(data);
$.ajax({
url : ajax_url,
data : data,
success : function(response) {
grid = $( "#ajax_filter_search_results" );
wpmafs.find(grid).empty();
if(response) {
for(var i = 0 ; i < response.length ; i++) {
var html = '<a class="grid-item destination" href="' + response[i].permalink + '">';
html += '<p class="grid-item-title">' + response[i].title + '</p>';
html += '<ul class="features">';
var features = response[i].features;
for(var k = 0 ; k < features.length ; k++){
if(k > 3) break;
html += '<li> <img width="8" height="8" src="/wp-content/uploads/2022/03/golf-escapes-sussex-uk-packages-benefits-copy.svg" class="attachment-medium size-medium">' + features[k]['point'] + '</li>';
}
html += '</ul>';
html += '<div class="bg-img">';
html += '<img src="' + response[i].image_url + '">';
html += '</div>';
html += '</a>';
wpmafs.find(grid).append(html);
}
} else {
var html = "<li class='no-result'>No matches found. Try a different filter.</li>";
wpmafs.find(grid).append(html);
}
},
error: function() {
grid = $( "#ajax_filter_search_results" );
wpmafs.find(grid).empty();
var html = "<li class='no-result'>It appears we're having some technical difficulties. Please try again shortly or call us.</li>";
wpmafs.find(grid).append(html);
}
});
});
这里是 AJAX 函数:
function wp_ajax_filter_search_callback() {
header("Content-Type: application/json");
if(isset($GET['sort_filter'])) {
$sortval = $GET['sort_filter'];
if($sortval == 'title'){
$orderby = $sortval;
$order = 'ASC';
} elseif ($sortval == 'ASC' || $sortval == 'DESC'){
$orderby = 'date';
$order = $sortval;
} else {
$orderby = 'title';
$order = 'ASC';
}
};
if(isset($_GET['country_filter'])) {
$location = $_GET['country_filter'];
if ($location != 'any'){
$loc_query[] = array(
'key' => 'country',
'value' => $location,
'compare' => "IN",
);
}
};
if(isset($_GET['region_filter'])) {
$region = $_GET['region_filter'];
if ($region != 'any'){
$region_query[] = array(
'key' => 'region',
'value' => $region,
'compare' => "IN",
);
}
};
$meta_query = array(
'relation' => 'AND',
$loc_query,
$region_query,
);
$args = array(
'post_type' => 'hotels',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => $orderby,
'order' => $order,
'meta_query' => $meta_query
);
$search_query = new WP_Query( $args );
if ( $search_query->have_posts() ) {
$result = array();
while ( $search_query->have_posts() ) {
$search_query->the_post();
$result[] = array(
"id" => get_the_ID(),
"title" => get_the_title(),
"permalink" => get_permalink(),
"image_url" => get_the_post_thumbnail_url('', 'medium-large'),
"features" => get_field('featured_offer')
);
}
wp_reset_query();
echo json_encode($result);
} else {
}
wp_die();
}
我之前在另一个网站上使用过这段代码,所以我知道它可以工作,但在这个例子中它不工作。
country_filter 和 region_filter 单选按钮有效。当您更改它们时,AJAX 调用运行,并且 wp_query 实际上被过滤。
但是,问题是 sort_filter 单选按钮由于某种原因无法使用。
因此,为了测试我一直在放置 print_r("some random bit of text")
并检查浏览器检查器中的网络选项卡,以查看该文本是否出现在请求中。在 if(isset($_GET['country_filter']))
和 if(isset($_GET['region_filter']))
下显示文本。但是,如果我把它放在 if(isset($_GET['sort_filter']))
下,它不会显示。
所以,很明显,AJAX 代码到达 if(isset($_GET['sort_filter']))
行并说“不,它没有设置”。但确实如此。
如果我在 JS 代码中使用 console.log() 来记录发送到 AJAX 调用的数据,我可以清楚地看到所选 sort_filter 正在发送单选按钮:
{action: 'wp_ajax_filter_search', sort_filter: 'title', country_filter: undefined, region_filter: undefined}
“网络”选项卡中的请求 URL 中也包含该信息,例如:
https://my.staging.url/wp-admin/admin-ajax.php?action=wp_ajax_filter_search&sort_filter=title
尽管如此,我还是无法获得 AJAX 代码以 $GET sort_filter 单选按钮值并在 WP_Query.
中使用它
非常感谢任何帮助。我要闭上眼睛一会儿,因为我已经完全筋疲力尽了,但我期待看到任何人都可以提供什么帮助,因为这真的让我感到困惑,而且最后期限很快就要到了。
非常感谢!
在你的ajax回调函数中你有
if(isset($GET['sort_filter'])) {
$sortval = $GET['sort_filter'];
应该是
if(isset($_GET['sort_filter'])) {
$sortval = $_GET['sort_filter'];
也就是说,您在 $_GET 的两次调用中都缺少 _
所以我已经为此工作了几个小时。其中大约 6 个没有中断,我不明白为什么这不起作用。
所以我有这个表格:
<div id="wp-ajax-filter-search" class="full">
<form action="" method="get">
<div class="flex filters-grid">
<div id="#sortBy" class="flex filters-dropdown">
<p class="filters-title">
Sort By
</p>
<div class="filters-options">
<input class="wp-drop-filter-item" type="radio" id="alphabetically" value="title" name="sort_filter">
<label for="alphabetically">
Alphabetically
</label>
<input class="wp-drop-filter-item" type="radio" id="datenew2old" value="ASC" name="sort_filter">
<label for="datenew2old">
Date Added (New to Old)
</label>
<input class="wp-drop-filter-item" type="radio" id="dateold2new" value="DESC" name="sort_filter">
<label for="dateold2new">
Date Added (Old to New)
</label>
</div>
</div>
<div id="#countries" class="flex filters-dropdown">
<p class="filters-title">
Country
</p>
<?php
// set up a new query for each category, pulling in related posts.
$destinations = new WP_Query(
array(
'showposts' => -1,
'post_type' => 'destinations',
'post_status' => 'publish',
'order_by' => 'title',
'order' => 'ASC'
)
);
if ($destinations->have_posts()):
?>
<div class="filters-options">
<input class="wp-drop-filter-item <?php echo $country_slug ?>" type="radio" id="any" value="any" name="country_filter">
<label for="any">
Any
</label>
<?php while ($destinations->have_posts()) : $destinations->the_post();
global $post;
$post_slug = $post->post_name;?>
<input class="wp-drop-filter-item country-option" type="radio" id="<?php echo $post_slug ?>" value="<?php echo $post->ID ?>" name="country_filter" >
<label for="<?php echo $post_slug; ?>">
<?php echo get_the_title(); ?>
</label>
<?php endwhile; ?>
<?php
// Reset things, for good measure
$destinations = null;
wp_reset_postdata();
?>
</div>
<?php endif; ?>
</div>
<div id="#regions" class="flex filters-dropdown">
<p class="filters-title">
Region <span class="extra">(Choose Country First)</span>
</p>
<?php
// set up a new query for each category, pulling in related posts.
$regions = new WP_Query(
array(
'showposts' => -1,
'post_type' => 'regions',
'post_status' => 'publish',
'order_by' => 'title',
'order' => 'ASC'
)
);
if ($regions->have_posts()):
?>
<div class="filters-options">
<input class="wp-drop-filter-item" type="radio" id="any-region" value="any" name="region_filter">
<label class="region-option" for="any-region">
Any
</label>
<?php while ($regions->have_posts()) : $regions->the_post();
global $post;
$post_slug = $post->post_name;
$country = get_field( "country", $post );
$country_slug = get_post_field( 'post_name', $country ); ?>
<input class="wp-drop-filter-item" type="radio" id="<?php echo $post_slug ?>" value="<?php echo $post->ID ?>" name="region_filter">
<label class="region-option <?php echo $country_slug ?>" for="<?php echo $post_slug; ?>">
<?php echo get_the_title(); ?>
</label>
<?php endwhile; ?>
<?php
// Reset things, for good measure
$regions = null;
wp_reset_postdata();
?>
</div>
<?php endif; ?>
</div>
</div>
</form>
<ul id="ajax_filter_search_results" class="destinations grid"></ul>
</div>
每当您更改其中一个单选按钮时,都会使用以下 JS 代码触发 AJAX:
var wpmafs = $("#wp-ajax-filter-search");
var wpmafsForm = wpmafs.find("form");
$(".wp-drop-filter-item").on("change",function(e){
e.preventDefault();
var sort_filter = $("input[name='sort_filter']:checked").val();
var country_filter = $("input[name='country_filter']:checked").val();
var region_filter = $("input[name='region_filter']:checked").val();
var data = {
action : "wp_ajax_filter_search",
sort_filter : sort_filter,
country_filter : country_filter,
region_filter : region_filter
};
console.log(data);
$.ajax({
url : ajax_url,
data : data,
success : function(response) {
grid = $( "#ajax_filter_search_results" );
wpmafs.find(grid).empty();
if(response) {
for(var i = 0 ; i < response.length ; i++) {
var html = '<a class="grid-item destination" href="' + response[i].permalink + '">';
html += '<p class="grid-item-title">' + response[i].title + '</p>';
html += '<ul class="features">';
var features = response[i].features;
for(var k = 0 ; k < features.length ; k++){
if(k > 3) break;
html += '<li> <img width="8" height="8" src="/wp-content/uploads/2022/03/golf-escapes-sussex-uk-packages-benefits-copy.svg" class="attachment-medium size-medium">' + features[k]['point'] + '</li>';
}
html += '</ul>';
html += '<div class="bg-img">';
html += '<img src="' + response[i].image_url + '">';
html += '</div>';
html += '</a>';
wpmafs.find(grid).append(html);
}
} else {
var html = "<li class='no-result'>No matches found. Try a different filter.</li>";
wpmafs.find(grid).append(html);
}
},
error: function() {
grid = $( "#ajax_filter_search_results" );
wpmafs.find(grid).empty();
var html = "<li class='no-result'>It appears we're having some technical difficulties. Please try again shortly or call us.</li>";
wpmafs.find(grid).append(html);
}
});
});
这里是 AJAX 函数:
function wp_ajax_filter_search_callback() {
header("Content-Type: application/json");
if(isset($GET['sort_filter'])) {
$sortval = $GET['sort_filter'];
if($sortval == 'title'){
$orderby = $sortval;
$order = 'ASC';
} elseif ($sortval == 'ASC' || $sortval == 'DESC'){
$orderby = 'date';
$order = $sortval;
} else {
$orderby = 'title';
$order = 'ASC';
}
};
if(isset($_GET['country_filter'])) {
$location = $_GET['country_filter'];
if ($location != 'any'){
$loc_query[] = array(
'key' => 'country',
'value' => $location,
'compare' => "IN",
);
}
};
if(isset($_GET['region_filter'])) {
$region = $_GET['region_filter'];
if ($region != 'any'){
$region_query[] = array(
'key' => 'region',
'value' => $region,
'compare' => "IN",
);
}
};
$meta_query = array(
'relation' => 'AND',
$loc_query,
$region_query,
);
$args = array(
'post_type' => 'hotels',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => $orderby,
'order' => $order,
'meta_query' => $meta_query
);
$search_query = new WP_Query( $args );
if ( $search_query->have_posts() ) {
$result = array();
while ( $search_query->have_posts() ) {
$search_query->the_post();
$result[] = array(
"id" => get_the_ID(),
"title" => get_the_title(),
"permalink" => get_permalink(),
"image_url" => get_the_post_thumbnail_url('', 'medium-large'),
"features" => get_field('featured_offer')
);
}
wp_reset_query();
echo json_encode($result);
} else {
}
wp_die();
}
我之前在另一个网站上使用过这段代码,所以我知道它可以工作,但在这个例子中它不工作。
country_filter 和 region_filter 单选按钮有效。当您更改它们时,AJAX 调用运行,并且 wp_query 实际上被过滤。
但是,问题是 sort_filter 单选按钮由于某种原因无法使用。
因此,为了测试我一直在放置 print_r("some random bit of text")
并检查浏览器检查器中的网络选项卡,以查看该文本是否出现在请求中。在 if(isset($_GET['country_filter']))
和 if(isset($_GET['region_filter']))
下显示文本。但是,如果我把它放在 if(isset($_GET['sort_filter']))
下,它不会显示。
所以,很明显,AJAX 代码到达 if(isset($_GET['sort_filter']))
行并说“不,它没有设置”。但确实如此。
如果我在 JS 代码中使用 console.log() 来记录发送到 AJAX 调用的数据,我可以清楚地看到所选 sort_filter 正在发送单选按钮:
{action: 'wp_ajax_filter_search', sort_filter: 'title', country_filter: undefined, region_filter: undefined}
“网络”选项卡中的请求 URL 中也包含该信息,例如:
https://my.staging.url/wp-admin/admin-ajax.php?action=wp_ajax_filter_search&sort_filter=title
尽管如此,我还是无法获得 AJAX 代码以 $GET sort_filter 单选按钮值并在 WP_Query.
中使用它非常感谢任何帮助。我要闭上眼睛一会儿,因为我已经完全筋疲力尽了,但我期待看到任何人都可以提供什么帮助,因为这真的让我感到困惑,而且最后期限很快就要到了。
非常感谢!
在你的ajax回调函数中你有
if(isset($GET['sort_filter'])) {
$sortval = $GET['sort_filter'];
应该是
if(isset($_GET['sort_filter'])) {
$sortval = $_GET['sort_filter'];
也就是说,您在 $_GET 的两次调用中都缺少 _