EN / ZH
Fixing the WordPress <?php if ( is_home() ) { ?> Not Working Issue

I’ve been modifying my blog’s template recently, which required using some WordPress functions. While working on showing specific sidebar content on certain pages, I ran into an issue. I’m documenting it here to avoid making the same mistake in the future.

Normally in PHP, to restrict a block of code to display only on the homepage, you’d write:

<?php if ( is_home() ) { ?>
Content that only shows on the homepage
<?php } ?>

The is_home() function returns true when on the homepage. This is the standard conditional for homepage-only display and can be inserted into any WordPress theme template, commonly used in the sidebar (sidebar.php), footer (footer.php), and similar files.

However, today while building the theme, I discovered that using <?php if ( is_home() ) { ?> to control the sidebar simply had no effect. I was pretty dense about it at the time — instead of looking at the code, I kept thinking I’d placed the if statement in the wrong location. I fussed over it for ages… The real reason turned out to be:

There was a query_posts() call before it that was causing it to fail.
The reason is that is_home, is_sidebar, is_aipsme — all these is_ prefixed functions are based on the main query loop,
and query_posts() causes them to deviate from the main loop.

The solution is to add wp_reset_query() before is_home():

<?php wp_reset_query(); if ( is_home() ) { ?>
This time it really does only show on the homepage
<?php } ?>