【发布时间】:2016-12-09 22:21:23
【问题描述】:
我创建了一个前端过滤器,它可以更改 url 中的查询变量。
http://example.com/events/?zone=strength&days=28th&locations=136
zone 和 days 是分类法,locations 是来自自定义字段的元查询。
我有 3 个选择输入,其中包含每个查询变量的列表,当您选择其中一个时,页面会使用 url 中的新查询重新加载,并且它按预期工作。
一切正常,但我认为让 ajax 重新加载循环而不是完整的页面加载会更好。
我的 jQuery(可能写得不好):
// function to split up URL queries
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
// on ready, set the select values to the url queries
var zone = getQueryVariable('zone');
var days = getQueryVariable('days');
var locations = getQueryVariable('locations');
if(zone) {
$(".event-filter .zone").val(zone);
}
if(days) {
$(".event-filter .day").val(days);
}
if(locations) {
$(".event-filter .location").val(locations);
}
// on select change, detect what changed and update url
jQuery('.event-filter select').on('change', function() {
var params = {};
if($(".event-filter .zone option:selected").val() != 'zone'){
var zone = $(".event-filter .zone option:selected").val();
params['zone'] = zone;
}
if($(".event-filter .day option:selected").val() != 'day'){
var days = $(".event-filter .day option:selected").val()
params['days'] = days;
}
if($(".event-filter .location option:selected").val() != 'location'){
var locations = $(".event-filter .location option:selected").val()
params['locations'] = locations;
}
// create new url
var path = window.location.pathname;
if ($.isEmptyObject(params)) {
var new_url = path;
} else {
var new_url = path + '?' + jQuery.param(params);
}
// reload page
window.location.href = new_url;
});
我想用 ajax 将 new_url 变量重新加载为 url,并使用新的查询变量使循环再次运行。
我的循环:
// Check if query vars are being used in the URL.
$days = get_query_var('days',FALSE);
$zone = get_query_var('zone',FALSE);
// Created tax_query array, supporting multiple arrays where all conditions must be met
$tax_query = array('relation' => 'AND');
// Set days variable with terms from the query var in url
if( ($days) ) {
$tax_query[] = array(
'taxonomy' => 'day',
'field' => 'slug',
'terms' => $days,
);
}
// Set zone variable with terms from the query var in url
if( ($zone)) {
$tax_query[] = array(
taxonomy' => 'zone',
'field' => 'slug',
'terms' => $zone,
);
}
// Check if locations query var is used
if(isset($_GET['locations']) && !empty($_GET['locations'])){
$locations[] = array(
'key' => 'event_location',
'value' => $_GET['locations'],
'compare' => 'IN'
);
}
// Load both taxonomy query and meta query arrays into their respective args!
$args = array(
'post_type' => 'event',
'posts_per_page' => -1,
'tax_query' => $tax_query,
'meta_query' => $locations
);
$events = new WP_Query( $args );?>
我的想法是,我应该使用上述循环创建一个函数,只要使用 jQuery/ajax 更改选择字段时调用该函数,而不是重新加载页面。这是正确的吗?
如何让它从更改后的 new_url jquery 变量中仅加载包含循环的部分,而不是整个页面?
【问题讨论】: