You shouldn’t have to globalize the main $wp_query
, only secondary queries.
Take the following example, if I have a very simple frontpage.php
template it would look like:
<?php get_header(); ?>
<?php get_template_part( 'templates/template', 'main-query' ); ?>
<?php get_footer(); ?>
I can then create a template found in /theme-name/templates/template-main-query.php
which has a normal Loop:
<?php if( have_posts() ) : ?>
<?php while( have_posts() ) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile; ?>
<?php endif; ?>
Note, I don’t need any kind of global query unless I want to access any of the query methods / properties like found_posts
or something of the like.
For secondary queries you could globalize the query but a better solution would be to include the template like so:
<?php get_header(); ?>
<?php
get_template_part( 'templates/template', 'main-query' );
$all_pages = new WP_Query( array(
'post_type' => 'page',
'posts_per_page'=> -1
) );
require_once( locate_template( 'templates/template-secondary-query.php' ) );
?>
<?php get_footer(); ?>
Then our template file would like like this:
<?php if( $all_pages->have_posts() ) : ?>
<?php while( $all_pages->have_posts() ) : $all_pages->the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php endwhile; ?>
<?php endif; ?>
If at all possible, it would be both cleaner and easier to just include the secondary new WP_Query
in the actual template file versus having your query in one file and loop in another. If I’m not mistaken, this is the method WooCommerce uses for their secondary queries in template files, they just include the new query at the top of the file.