get_template_part() not firing within a switch statement when template has new WP_Query

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';
}

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)