How to Use WordPress 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 WordPress conditional tags were her favorite WordPress functions for their simplicity and ease of use — they read just like English. We agree with her on that. They’re great. To explain them to you in more depth, we’re sharing a chapter of Up and Running here on WPShout. Let’s get to business understanding conditional tags in WordPress!

The Ultimate Way to Learn WordPress Development Concepts

Get Up and Running Today!

Up and Running is our complete “learn WordPress development” course. Now in its updated and expanded 3rd Edition, it’s helped hundreds of happy buyers learn WordPress development the fast, smart, and thorough way.


Key Takeaways about WordPress Conditional Tags:

  • WordPress’s conditional tags are prewritten WordPress functions that test several dozen distinct criteria, mostly about the nature of the post or posts that have been retrieved for processing.
  • Each conditional tag returns a boolean (either true or false) based on the result of its check. Combined with PHP if-statements, this allows easy conditional code execution in either plugins or themes.
  • Some conditional tags don’t function exactly as their name might suggest; this chapter covers several of these cases.

One of the most straightforward, dependable, and useful things in WordPress is “conditional tags.” Several of our interviewees mentioned conditional tags being their favorite WordPress functions for their simplicity and ease of use—they read just like English—and 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 in WordPress 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. They’re really useful for making yes-or-no type “conditional” decisions when you need to.

For example, if we write something like if ( is_sticky_post() ) {} in The Loop, 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 
/* Environment: We're inside a theme template file that uses The Loop, like home.php or index.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…”

A Few WP Conditional Tags Worth Discussing

WordPress has over 50 conditional tags. We won’t list them all here, but we will call out a few that are either particularly useful or particularly likely to cause confusion (or both).

Useful WordPress Conditional Tags

  • is_single(): Is true if the page that’s currently rendering is made up of a single post, of any post type except Attachment (a media file) or Page.
  • 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 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.

Possibly-Confusing Conditional Tags

  • 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.
  • is_dynamic_sidebar(): Is true if any of the currently registered sidebars (widget areas) have active widgets. Not quite what you’d expect, from the name.
  • 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://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 words, 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, at https://codex.wordpress.org/Conditional_Tags.

Passing Parameters to Conditional Tags in WordPress

Many conditional tags that evaluate the current post—such as is_singular(), is_home(), and is_page()—have a shared feature: they accept a function parameter that lets you specify an additional attribute that the post must satisfy.

Depending on the function, this attribute can check for the post’s ID, post type slug, or title. Here are a few examples:

  1. is_singular( 'movie-review' ) checks for a single post of type Movie Review.
  2. is_page( 'Weekly News Roundup' ) checks for a Page titled “Weekly News Roundup.”
  3. is_single( 5 ) checks for a single post with a post ID of 5.

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 common use cases.

Using Conditional Tags in Template Files

Conditional tags are very commonly used in WordPress theme development. Sometimes one element in a template hierarchy file 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. Maybe Pages and Posts display identically in all other respects—so we don’t want to go to the trouble of creating a page.php that’s 99% the same as the index.php we already have. Instead, we want to keep index.php as our only template file, no matter what post type is displaying.

We can do:

/* Environment: We're inside The Loop, in index.php */

<?php if ( ! is_page() ): ?>
	<span class="meta-date">
	    <?php the_date(); ?>
	</span>
<?php endif; ?>

A Note on Conditional Tags and the WordPress Template Hierarchy

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

Taking the example above to its extreme: you can use WordPress conditional tags as a substitute for the entire WordPress template hierarchy! You could just have your whole theme in index.php, and use conditional tags to make the same decisions that the template hierarchy normally does.

To actually structure your theme that way is not a great idea, but knowing that it’s possible—and the equivalencies between conditional tags and the template hierarchy—should help you better understand both. For a more visual take on the subject, check this diagram (one of our favorites): https://wphierarchy.com/.

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 custom page on your website which looks and behaves very uniquely. Perhaps it has a lot of interactive effects, a different look-and-feel, and so on.

To achieve those effects, the page will have lots of custom JavaScript files and CSS stylesheets—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:

/* Environment: We're in the active theme's functions.php (or perhaps a PHP file in a "Special Page" plugin) */

function wpshout_special_page( ) {
    if ( ! is_page( 'special-page' ) ) {
    	return;
	}

    wp_enqueue_script( 
        'special_js', 
        get_stylesheet_directory_uri().'/special.js'
    );
    wp_enqueue_style( 
        'special_css', 
        get_stylesheet_directory_uri().'/special.css'
    );
}
add_action( 'wp_enqueue_scripts', 'wpshout_special_page' );

Here, we do our enqueuing as normal, but we’ve preceded the enqueue commands with an if-statement: if the current page isn’t our “special page,” the function returns early and 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? 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.

Note on WordPress 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.

As a result, you can’t dependably use WordPress conditionals until the WordPress “factory” process has marked the posts_selection action. (Here’s a full list of actions marked by WordPress and their order: https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request.)

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

Most of the time, this will be a non-issue, but it’s good to know what you can and can’t do, for the rare case in which this knowledge becomes very important.

Wrapping Up

Conditional tags are a very easy-to-use way to create conditional functionality of all sorts within WordPress. They’re one of WordPress’s gifts to its developers, so enjoy!

Summary Limerick

For code that runs if something’s true,
Conditional tags are for you.
With many a test,
This system is_ best
At dictating what (not?) to do.

Quiz Time!

  1. Every WordPress conditional tag returns:
    1. HTML markup
    2. A boolean value
    3. A WordPress post object
  2. Conditional tags would not be useful for:
    1. Loading stylesheets and JavaScript onto only those pages where they are needed
    2. Adding social media icons to the site’s footer on every Post (but not on Pages)
    3. Deleting every image uploaded to the site that is wider than 1000px
  3. if ( is_single() ) { echo 'Hi!'; } will echo “Hi!” if:
    1. The webpage being rendered contains a single post of type Page
    2. The webpage being rendered contains a single post of type Movie Review
    3. The webpage being rendered contains only one Loop

Answers and Explanations

  1. B. In other words, when you execute a conditional tag, you get back either true or false.
  2. C. WordPress’s conditional tags generally relate to properties like post type, post title, and author, not to the dimensions of media attachments.
  3. B. is_single() returns false—even when only a single post is being processed—if the post being processed is of post type Page or Attachment. When the post bundle being processed consists of a single post of any other post type (including custom post types, such as “Movie Review”), is_single() returns true.

Seem like a good way to learn WordPress development?

Get Up and Running Today!

You just read a selection from Up and Running, our complete “learn WordPress development” course. Now in its updated and expanded 3rd Edition, it’s helped hundreds of happy buyers learn WordPress development the fast, smart, and thorough way.

Image credit: JD Hancock


2 Responses

Comments

  • A Grateful Reader says:

    I think it would do well for your quiz at the end to re-word the second question for the quiz at the end.

    Conditional tags are not a creation of WordPress, as such, the way the question is worded, there is a perception in which there is no correct answer.

    The answer C, if read as a full sentence – Conditional tags would not be useful for: Deleting every image uploaded to the site that is wider than 1000px – is poorly worded and likely has no sense to many programmers as conditional tags could be extremely useful in the process of deleting every image uploaded to the site that is wider than 1000px.

    I think what the question is trying to ask is if there is a conditional tag that is a part of WordPress Core which would be useful in image dimension checks.

    Thanks for the informative article!

Pingbacks

Add a Comment

Your email address will not be published. Required fields are marked *