0

I want the normal search result to be available when using the wp_ajax action. Is there a way to do execute the normal WP_Query for the parameters that are available in the current request?

This is my current code:

add_action('wp_ajax_nopriv_update_search', 'ajax_update_search');
add_action('wp_ajax_update_search', 'ajax_update_search');
function ajax_update_search() {
    global $wp_query;
    get_template_part('loop');
    exit;
}

My current code doesn't return anything, because $wp_query seems not to be setup. Is it possible to get the default $wp_query for the parameters of the current request?

(Note: I don't want to setup the parameters to WP_Query myself. I want the normal main query to fire.)

Update

This seems to be working. But I'm not sure that I'm doing it the right way. Can someone confirm please. I want as little overhead as possible.

add_action('wp_ajax_nopriv_update_search', 'ajax_update_search');
add_action('wp_ajax_update_search', 'ajax_update_search');
function ajax_update_search() {
    global $wp_query, $wp;
    $wp->init();
    $wp->parse_request();
    $wp->query_posts();
    $wp->register_globals();
    get_template_part('loop');
    exit;
}

Update 2

For some reason I get unpublished posts in the result. So my solution above is not complete. But it seems to be close. What could cause unpublished posts to be returned?

0

You can try to store $wp_query in a cookie or in a session variable.

global $wp_query;
setcookie('my_wp_query', $query_string);

or

global $wp_query;
$_SESSION['my_wp_query'] = $query_string;

and use that in you ajax function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.