I didn't want to use AJAX for this, but I ended up having to. The solution I came up with is to use AJAX to generate a 'redirect' URL and append query arguments using add_query_arg()
then return the URL with the query parameters and use window.location.href
to redirect the user. The page is redirected with the query arguments appended and then on page load WP_Query();
is ran with the s=
parameter containing the query parameters.
Probably not the most efficient way, or even the proper way, but it gets the job done. If anyone has another solution, I'd love to hear it.
Example PHP Function:
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();
}
And then the 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);
}
}
});
});
Please note the above code is NOT put into production use, it was just written/modified to show an example solution to the question at hand.