When is $wp_query initialized and how to override it?

wordpress

Solution

You are creating a new `WP_Query` object and saving it to `$results`. That is where the results of your query will be, not in `$GLOBALS['wp_query']`. Of course it doesn't overwrite `$wp_query`. They are different things. Try `var_dump($results)` instead.

You can overwrite `$wp_query` by creating a new `WP_Query` object like so: `$wp_query = new WP_Query($query_args);`. But that isn't efficient. You run two queries when you only need one. The better way to do it is to hook into `pre_get_posts`. Something like:

function alter_query_so_15250127($qry) {
   if ( $qry->is_main_query() && is_page('featured-posts-page') ) {
     $qry->set('post_type','page');
     $qry->set('post_parent',41);
   }
}
add_action('pre_get_posts','alter_query_so_15250127');

The `if` conditional is very important. You need to use that line to make sure the filter fires only on the page(s) you want it to fire on. Your question does not have enough detail for me to work out the precise conditions.

Problem

I am trying to write a new query function using `WP_Query` object. I created a new template file and put the followings: ``` $query_args = array( 'post_type' => 'page', 'post_parent=41', ); // The Featured Posts query. $results = new WP_Query($query_args); ``` But whatever arguments I use, the query does not change. It looks as if the query is already initialized and creating a new `WP_Query` does not have any effect on the existing query. The only wordpress function called before my code is `get_header()` which does not include any call to `WP_Query` or `query_posts`. I put the following line to find out what the actual sql query is: ``` echo $GLOBALS['wp_query']->request; ``` The actual sql query is: ``` SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND (wp_posts.ID = '14') AND wp_posts.post_type = 'page' ORDER BY wp_posts.post_date DESC ``` This query does not change when I change my `$query_args`. I wonder when the global variable `$wp_query` is initialized and what should I do to use my own query?

Original source