I am in the process of rewriting a lot of my code and restructuring a lot of my theme files to use template parts (i.e. using get_template_part()
). I've come upon a situation where I want to use the same template parts whether I'm using the main query or a secondary custom query (using WP_Query
). The template parts also use core functions that rely on the main query (such as conditionals).
I can get around the problem by overwriting the main query (or overwriting the $wp_query
global which holds the main query, the main query still exists) with my custom query and resetting the main query once I'm done. This also means I can use the same loop for the main query and my custom queries. For example:
// Query
if ( $i_need_a_custom_query ) {
$wp_query = new WP_Query($custom_query_args);
}
// The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
// Do some loop stuff
// and call some functions that rely on the main query
// End the loop
endwhile; endif;
// I'm done so reset the query
wp_reset_query();
This works. No problem at all, but it seems a bit of a hack to me. So my question is:
- Am I right to be weary of overwriting the main query like this?
- Are there any side effects I'm missing?
- And am I correct in assuming that calling
wp_reset_query()
isn't costly (i.e. it isn't actually re-running the query but simply resetting the globals which are still around somewhere)?
Edit to clarify:
I am only using the custom queries in question as secondary queries, that's the whole point of the question. I want to use the same template wether I am using a custom secondary query or using the main query. I understand that what I am doing is essentially the same as using query_posts()
, which is a bad idea. As far as I'm aware and broadly speaking, the 2 drawbacks to using query_posts()
are 1. Performance, which isn't an issue because I am only doing this when running a secondary custom query anyway and 2. Unintended consequences from changing the global $wp_query, which is exactly what I do want to happen (and as I said is actually working perfectly).