Is it possible to run pre_get_posts inside the ajax callback? I want to change the query after the ajax run

here my code

 function repeater_dynamic_query( $query ) {
  global $post;
  if ( $query->query['post_type'][0] == 'post' ) {
    $query->set( 'tax_query', array(
                                  'taxonomy' => 'location',
                                  'field' => 'slug', 
                                  'terms' => 'london',
                                  'include_children' => false
                              ) );
    $query->set( 'orderby', 'rand' );
    $query->set( 'post__not_in', array($post->ID) );
    $query->set( 'no_found_rows', true );

Here my ajax callback

add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );
function my_ajax_action_callback(){
    add_action( 'pre_get_posts', 'repeater_dynamic_query' ); //run pre_get_posts
    wp_die(); // required. to end AJAX request.
  • have you considered using the REST API instead? What's the problem you're trying to solve with this? You can't change a query after it's ran without time travel, you have to do it before
    – Tom J Nowell
    Commented Oct 18, 2022 at 10:14

1 Answer 1


Not the way you're doing it, no.

When the pre_get_post action is run any WP_Query queries run will be modified by the callback. Actions are not persistent, so when you run add_action() inside an AJAX callback that action is only going to be applied for that request, and you're not running any queries in the AJAX response so there's nothing to modify.

If you want to make an AJAX request that modifies all future queries then you need to save some record in the database in response to the AJAX request, and then inside your pre_get_posts callback you need to check for the existence of that record before conditionally applying the changes you want to make.

If you want to change all queries for the current user in response to an AJAX request then that becomes more complicated and you'll likely need to use cookies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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