Run again current query via ajax but changing a var

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:

// in functions.php or in plugin
function my_custom_query( $posts_per_page = 10 ) {
  $args = array(
    'posts_per_page' => $posts_per_page,
    // other args here
  ); 
  return new WP_Query( $args );
}

// then inside the page
$query = my_custom_query();
while ( $query->have_posts() ) { $query->the_post();
  // your loop code here
}

// and handling ajax action
add_action('wp_ajax_the_function_here', 'my_ajax_loop');
add_action('wp_ajax_nopriv_the_function_here', 'my_ajax_loop');
function my_ajax_loop() {
   $query = my_custom_query( -1 );
   while ( $query->have_posts() ) { $query->the_post();
     // your loop code here
   }
   die();
}

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:

add_action('wp_enqueue_script', 'add_my_scripts');

function add_my_scripts() {
  // here I'm assuming the javascript file where you have the code you posted
  // is called 'myscript.js' and resides in 'js' subfolder inside theme folder
  wp_enqueue_script('my_script', get_template_directory_uri() . '/js/myscript.js');
  global $wp_query;
  $qv = $wp_query->query;
  wp_localize_script('my_script', 'my_script_data', array('query' => $qv) );
}

After that, in the js file you can:

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
    query: my_script_data.query // Defined by 'wp_localize_script'
  },
  success: function(data, textStatus, XMLHttpRequest) {  
    jQuery('#bodyForOutput').html(data);  
  },  
  error: function(MLHttpRequest, textStatus, errorThrown) {
    alert(errorThrown);
  }
});

Now you can hande the ajax request in like so:

// and handling ajax action
add_action('wp_ajax_the_function_here', 'my_ajax_loop');
add_action('wp_ajax_nopriv_the_function_here', 'my_ajax_loop');
function my_ajax_loop() {
   $args = (array) filter_var(INPUT_POST, 'query');
   $args['posts_per_page'] = -1;
   $query = new WP_Query($args);
   while ( $query->have_posts() ) { $query->the_post();
     // your loop code here
   }
   die();
}

Leave a Comment