WordPress’s Conditional Tags

if is stormtrooper moonwalk | wordpress conditional tags

One of the most straightforward, dependable, and useful things in WordPress is what the Codex calls “Conditional Tags.” In her interview for Up and Running, Helen Hou-Sandí said conditional tags were her favorite WordPress functions for their simplicity and ease of use — they read just like English. We’re pretty much on board.

Here, we’ll discuss the workings of conditional tags, including a few subtle points; list of some of the most useful tags, as well as some of the most confusing; and end with a few examples.

How Conditional Tags Work

Conditional tags are WordPress functions that return boolean values when called, based on different criteria.

Conditional tags are WordPress functions that return a boolean value — either true or false — when called, based on different criteria. These criteria are usually spelled out in the function names.

Conditional tags can be called from anywhere in WordPress — themes, plugins, you name it — and are really useful for making basic yes-or-no type “conditional” decisions when you need to.

For example, write something like if ( is_sticky_post() ) in The Loop, and the markup inside the if-statement will show up only if the current post is sticky—”stuck” to the top of your blog index, a bit like a pinned tweet—and not otherwise:

<?php 
if ( have_posts() ) :
	while ( have_posts() ) :
		the_post(); 

		// (Regular Loop contents will go here)

		if ( is_sticky_post() ) :
			// This code will execute *only* for sticky posts!
		endif;

	endwhile;
endif;

Note the syntax of our call to is_sticky_post() Most WordPress conditional tags start with is_, because they’re status checks. And since they’re most often linked up with if()-statements, they really do read like English: “If is sticky post” then what?

A Few of the Most Useful and Confusing Conditional Tags

There are, all told, well over 50 conditional tags in WordPress. Listing each one here would be an exercise in boredom for both of us, so here we’ll just call out those that are interesting and noteworthy — either for their usefulness or their ability to cause confusion (or both).

Useful

  • is_single() — Is true if the page that’s currently rendering is made up of a single post, of any post type except attachment. This one can actually take function parameters to specify numeric or string parameters that the single post must satisfy.
  • is_page() — Is true if the item being displayed is a single post of WordPress’s default “Page” post type.
  • is_singular() — Similar to is_single(), but it’ll also be true when you’re showing a post of type Attachment (a media file) or Page. Is equivalent to is_single() || is_page() || is_attachment(), where || means “or.”
  • is_archive() — Is true if the current page is displaying a set of archives, whether for an author, a date range, a tag, category, etc.
  • is_main_query() — Is true if the current query is the main query for the page. This one’s really useful when you’re trying to hack the post-fetching process at pre_get_posts — though, in that case, you’re not using it globally, but as a method on the query object passed to you from the filter.

Confuseful

  • is_admin() — Is true when you’re in the administration area of a WordPress site. This can be a little confusing, because you might mistakenly believe that it’ll tell you if the current user is an Administrator — it does not.
  • is_dynamic_sidebar() — Is true if the currently registered sidebars (widget-areas) have any active widgets. Kind of what you’d expect, but not quite…
  • is_home() — This one’s confusing. You might think that is_home() will tell you if you’re currently rendering the root of your WordPress site, like http://www.example.com. This is not exactly the case: WordPress allows you to have either a bunch of blog posts at your site’s root, or a “Static Front Page.” If your site has a static front page, your is_home() will be false on the site’s homepage (example.com), and true on the site’s blog index (example.com/blog). In sum, is_home() really amounts to is_blog_posts_index() — which, sadly, does not exist.
  • is_front_page()is_front_page() is true if you’re on a static front page, or on your blog index if you’re not using a static front page. In other word, it’ll always be true at example.com, whatever that page has on it. As you can see, it’s quite a bit more like “is home?” than is_home() itself.

That’s just a partial list of the conditional tags that start with is_. There are also a few that start with has_ (and some that start with neither). The canonical list is on the Codex itself: the Codex list.

Some Use Cases for WordPress Conditional Tags

There are infinite ways to combine the 50+ conditional tags WordPress supplies to do interesting things. Here are a few somewhat-similar and common uses.

Using Conditional Tags in Template Files

Conditional tags are very commonly used in WordPress theme development. Sometimes you have one element on a page in the template hierarchy that basically works, but is showing up in a few situations where you don’t want it.

For example, let’s say we don’t want to display the date on pages, but we do on all other post types:

/* Environment: We're in single.php */
<?php if ( ! is_page() ): ?>
<span class="meta-date">
    <?php the_date(); ?>
</span>
<?php endif; ?>

A Note on Conditional Tags and the Template Hierarchy

You could build the template hierarchy’s decision-tree yourself using conditional tags.

One thing I like to point out is that the template hierarchy is basically the same thing as a decision-tree you could build yourself using these conditional tags. You could just have your whole theme in index.php and use these conditional tags to do what the template hierarchy does.

Actually doing that is not really a great idea; but knowing that it’s possible, and the equivalencies between conditional tags and the template hierarchy, helps you better understand both, I think. For a more visual take on the subject, check this diagram (one of our favorites):

WP_CheatSheet_TemplateMap

Enqueuing Special Stylesheets or JavaScript Files

Conditional tags make it easy to enqueue scripts and styles only on pages where they’re needed.

Sometimes, you may want a big custom page on your website—one of those fancy pages that people link to from all over the internet, with lots of wooshy-wow effects, and so on.

To achieve those effects, the page has lots of custom scripts and styles, which you only need for this one page. Loading them across the site will slow every other page down for no good reason. Fortunately, with conditional tags it’s easy to only enqueue them for one page alone:

add_action( 'wp_enqueue_scripts', 'wpshout_special_page' );
function wpshout_special_page() {
    if ( is_page( 'special-page' ) ) {
        wp_enqueue_script( 
            'special_js', 
            get_stylesheet_directory_uri().'/special.js'
        );
        wp_enqueue_style( 
            'special_css', 
            get_stylesheet_directory_uri().'/special.css'
        );
    }
}

Here, we do our enqueuing as normal, but we’ve wrapped the enqueue commands in an if block: if the current page isn’t our “special page,” our extra scripts and styles aren’t loaded.

Notice that our is_page() call actually has to pass two tests:

  1. Is it a Page-type post? This is what is_page() itself checks for.
  2. Does the page have the slug special-page? To test for this, we passed 'special-page' in as a parameter for is_page().

Forcing our is_page() call to satisfy both of these conditions is what makes it possible to restrict our scripts and styles only to our one particular page.

is_admin() is another obvious case where plugins may need, or want, to do similar checks.

Note on Conditional Tags and Global State

WordPress’s global state has to be set before you can properly use conditional tags.

Conditional tags access WordPress’s global state—the “way things are” in the background—and that state has to be set before you can properly use them.

First, you can’t dependably use WordPress conditions until the WordPress “factory” process has marked the posts_selection action. (Here’s a full list of actions marked by WordPress and their order.)

This means that some commonly used actions can’t be used simultaneously with conditional tags. Specifically: setup_theme, init, register_sidebar, and pre_get_posts are a few of the more common actions for which these conditional tags aren’t accessible. However, about half the hooks that WordPress typically fires, and all the template-rendering that is does, happen well after the template tags are loaded, and so they’re perfectly useful there.

Most of the time, this will be a total non-issue, but it’s good to know what you can and can’t do. This is one of those things that’s just good to be aware of for the one time in 50 it bites you and confounds.

WordPress Conditional Styles: Learn ’em, Use ’em, Love ’em

WordPress conditional functions are so straightforward, ubiquitous, and useful that it’s easy to forget about them and how much easy value they provide. Hopefully you’ll think to look for the right one next time you think, “Yes, do it like this but only not in this one case…” or “but I only want it to show up when…” They’re great for that, and they help make WordPress as powerful as it is. Happy hacking!

Image credit: JD Hancock


2 Responses

Pingbacks

Share This