我不想为此使用 AJAX,但我最终不得不这样做。我想出的解决方案是使用 AJAX 生成“重定向”URL 并使用 add_query_arg() 附加查询参数,然后返回带有查询参数的 URL 并使用 window.location.href 重定向用户。该页面被重定向并附加了查询参数,然后在页面加载时WP_Query(); 使用包含查询参数的s= 参数运行。
可能不是最有效的方法,甚至不是正确的方法,但它可以完成工作。如果有人有其他解决方案,我很乐意听到。
示例 PHP 函数:
public function user_redirect_by_search() {
$search_arr = array();
parse_str($_POST['search_data'], $search_arr);
$return = array();
$post_type_arr = array();
$post_type_count = 0;
foreach($search_arr['post_type'] as $post_type) {
$post_type_count++;
$post_type_arr[$post_type_count] = $post_type;
}
$redirect_url = add_query_arg( array('post_type' => implode(",", $post_type_arr), 'keywords' => $search_arr['s']), $search_arr['page_url']);
$return['status'] = 1;
$return['redirect_url'] = $redirect_url;
echo json_encode($return);
die();
}
然后是 jQuery:
// Post keyword search
jQuery('#searchform').on('submit', function(e) {
e.preventDefault();
var search_data = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: ajaxurl,
dataType: 'json',
data: {"action": "user_search", search_data},
success: function(data) {
if(data.status == 1) {
window.location.href = data.redirect_url;
//console.log(data);
} else {
alert("Oops, an error occurred. Please try again or contact the plugin developer.");
console.log(data);
}
}
});
});
请注意,上述代码并未投入生产使用,只是为了显示手头问题的示例解决方案而编写/修改。