The problem: The code never cleans up after its queries
Your queries are currently missing several things:
- The code never checks that the query found any posts via
if ( $q->have_posts() )
- There are no calls to
wp_reset_postdata
When you call either the_post
or setup_postdata
, you change the global $post
variable. This can cause issues in any code that runs after the loop as the post context is no longer the post of the page, but the last post of the query loop.
Calling wp_reset_postdata
should fix this, but it must only be called if the query found posts. If this isn’t done, then this can cause issues or slowdown in nested loops, and other unanticipated behaviour.
Here is an idealised WP_Query
loop:
$args = array(
// ....
);
$q = new \WP_Query( $args );
if ( $q->have_posts() ) {
while( $q->have_posts() {
$q->the_post();
// display post
}
wp_reset_postdata();
} else {
echo 'no posts found';
}