I have custom query which is $query
. The input is based on form input. The query has already run on a page, but after that I’d like to run it again without a page reload, so with AJAX (when the users selects a tab (Bootstrap)).
The thing is that I need to change the query var posts_per_page
to -1
.
The code to do something when the tab is selected is:
$('#myTab').on('shown', function () {
// Do stuff here
})
Now within that function I can do
jQuery.ajax(
{
type: 'POST',
url: ajaxurl, // example.com/wp-admin/admin-ajax.php is defined in my js file
data:
{
action: 'the_function_here',
ajaxnonce: YTajax.ajaxnonce, // Also defined
},
success: function(data, textStatus, XMLHttpRequest)
{
jQuery('#bodyForOutput').html(data);
},
error: function(MLHttpRequest, textStatus, errorThrown)
{
alert(errorThrown);
}
});
But I don’t really know how to make use of $query
which is already defined. I only need to alter the posts_per_page
. Can I do this with set_query_var
? Or is that only usable for the main loop?
You have to note that an ajax request is an entirely new http request, so the
$query
variable is defined in the page that send the ajax request but will be not set in the page that receive the request.That means that you have completely recreate the query and not change a param.
That said, you have 2 possibilities:
1: Query is a custom one
If the query is a custom one (you create it using
WP_Query
) you can write a function that return that query and call it from the page and from the function hooking in the ajax action:2: Query is the main query
If you want to replicate the main query changing one or more param, cosider to pass the query vars to the script via
wp_localize_script
and the pass them via ajax to the function that handle the ajax action, something like:After that, in the js file you can:
Now you can hande the ajax request in like so: