If you’re a WordPress developer or a DIY WordPress geek, you might have came across this problem when WordPress conditionals like is_single(), is_home(), is_page() etc. stop functioning at some or all instances. Such problem may arise due to the use of a custom WordPress Query (WP_Query or query_posts) in your WordPress theme or some plugin on your WordPress, and when you want to control something on your theme using WordPress conditionals, they may not work as expected.

Why this happens?: Actually the functionality of WordPress conditionals like is_single(), is_home() etc. depends on the default, main WordPress query. Using custom queries through query_posts or WP_Query function changes the main query for a page (home, single, page, attachment, archive etc.) and it may cause these conditionals stop working.

But it doesn’t mean it doesn’t have a solution or fix. You can always bring back the default main query to get WordPress conditional start working again, even without being a professional WordPress developer.

WordPress conditionals not working: The Fix

Using wp_reset_query() brings the main WordPress query back and make the WordPress conditionals work again like a charm. If you’re not a developer and looking for a quick fix, your should simply use wp_reset_query() just above your conditional. Adding this snippet will quickly fix this problem.

<?php wp_reset_query(); ?>
<?php if( is_single() ) { ?>
    ...
} ?>

Developer Tips: Using wp_reset_query() just after your custom query loop will keep you and your clients away from having any problem with WordPress conditional anywhere in your Themes. The below example illustrate how to do that:

<?php $my_wp_query = new WP_Query('posts_per_page=3');
while ($my_wp_query->have_posts()) : $my_wp_query->the_post(); ?>
    <h2><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
<?php endwhile; ?>
<?php wp_reset_query(); ?>

Some useful things to keep in mind while working with custom WordPress queries:

Avoiding the use of $wp_query global with your new WP_Query object will keep you away from any problem with queries. For example, name your new query $my_secondary_query instead of $wp_query global. This way, all of these conditionals will continue to work fine on the main query without having to call wp_reset_query(). As a bonus, you can also use these conditional tags on your secondary queries, such as $my_secondary_query->is_single().

Similarly, you can also use wp_reset_postdata() instead of using wp_reset_query() after going through the secondary or custom loop to restore the $post global to the main query.

Hope you find it useful. Also read how to Display Dynamic Timestamp in WordPress.