WordPress Conditional Tags

What the Weatherman Can Teach You About WordPress Conditional Tags

How many times have you flipped on the morning news to get the day’s forecast? Sure, you can guess at the basics (if it’s a summer day in Texas, it’ll be hot, right?), but we still like the extra details a meteorologist can offer. 

Is it raining ? Are water restrictions in effect? Will I die of heat stroke if I run after work? Is it raining men?

Each of these details give us the information we need to make the best decisions for our day. So, if it’s going to rain, I’m going to cancel pool time and head to the movies instead. If we’re hitting a record high, I’m going to suck it up and jog on a treadmill instead of pounding hot pavement.

In much the same way, we can use WordPress conditional tags to show when certain situations ring true and then use that knowledge to change the default behavior. Even better, WordPress conditional tags are always 100% accurate, unlike meteorologists. :)

Rain Down Some Details, Carrie

You’ll typically find WordPress conditional tags used in conjunction with PHP conditional statements (i.e. if/else). It’s a big conditionals party, really.

You can use these conditional checks in your theme’s functions.php file or in individual theme template files. We’ll talk a little more about that later.

Start with the Basics

While my WordPress site might not care if it’s raining, perhaps it does care when a single post is displayed. Here’s a basic example of how WordPress can know if that’s true:


if ( is_single() ) {

echo 'Hey there, singleton!';

}

The is_single() tag returns true if any single post, attachment, or custom post type page is being displayed. This bit of code isn’t very useful, but it does demonstrate a PHP conditional statement (if) with a WordPress conditional tag ( is_single() ).

A Real Example

You can use these conditional checks anywhere in a theme, but not every place makes sense. For example, if I’m working on a single page template, it wouldn’t make sense to ask the page if it’s single (i.e. is_single() ). That’s like asking a drop of rain if it’s wet.

Instead, we should ask when we don’t know the answer, like in our theme’s functions file. Here’s an example:

Write it in code:


if ( is_single() && is_author('Carrie') ) {

$classes[] = 'giddyup';
return $classes;

}

Say it in English:

If the post being viewed is single AND Carrie is the author, then apply a special body class called ‘giddyup’.

The Bigger Picture

If we stuck the code above in our theme’s function file, it would do a BIG FAT NOTHING. Why? Because to “interfere” with the default WordPress output, we need to hook into the code using an action or a filter. (If you’re using a theme framework like Genesis, you’ll have even more actions and filters at your disposal).

In order for our code to work, we need to make a function out of it and then use a filter to tell WordPress where/when to pull the trigger on our code.

Write it in code:


add_filter( 'body_class', 'my_body_class' );

function my_body_class( $classes ) {

if ( is_single() && is_author('Carrie')() ) {

$classes[] = 'giddyup';
return $classes;

}
}

Say it in English:

At the point where WordPress assigns a class to the <body> tag, add a custom body class of ‘giddyup’, but only if it’s a single post authored by Carrie!

Learn More About WordPress Hooks

Nathan Rice wrote a great article breaking down WordPress Action Hooks. Read it if you’d like to increase your grasp on the subject.

I Wanna Get Absolutely Soaking Wet

This is a mere sprinkling of what you can do with WordPress conditional tags. If you want to delve into plugin development or theme customizations, you’ll need to spend time immersing yourself in conditionals.

Did I overdo the water words? You’re welcome.

Here’s a link so you can bookmark the official codex page: WordPress Conditional Tags. Visit it and visit it often.

Happy coding!

Image credits for “It’s Raining Men Wallpaper” to Jordan LaPointe.

7 day free trial

Carrie Dils

I’m a recommended Genesis Developer with 15+ years experience in web design and development. I'm creative, resourceful, and ready to put my mind to your project. Want to discuss your WordPress project? Let's talk!

Comments

  1. Brad Dalton - says

    Very nice tutorial for beginners Carrie.

    Easy to follow and understand.

    Here’s another version which i’ve modified slightly which is why i use Github Gists on my site.

    add_filter( ‘body_class’, ‘my_body_class’ );

    function my_body_class( $classes ) {

    if ( is_single() && is_author(‘Carrie’) ) {

    $classes[] = ‘giddyup’;
    return $classes;

    }}

    • says

      Whoops! I missed that closing bracket – thanks for the heads up! I do like using gists on some of my longer snippets. I just feel kinda dorky using it for small samples like this post. Could definitely stand some better formatting, though. :)

      • Brad Dalton says

        Looks nicer without the Gist but when you copy and paste it, the apostrophes can change and cause errors after saving the file. Also if someone comes and republishes the code and there’s a small mistake, you can’t change it on their site unless its in your Gist.

  2. says

    Hello Carrie

    Thanks for the new tutorial. I’ve learned a lot from your previous tutorials, I find them easy to understand. After I watched your tutorial, and Brian Gardner’s tutorial about widget areas

    http://www.carriedils.com/add-widget-area-below-nav/

    http://www.briangardner.com/home-widget-area-eleven40/

    I made a YouTube video about conditional tags. I’m not sure if you link to YouTube, if you do here’s the link. Your visitors might find it useful. Near the end of the video I included some slides explaining how it works.

    http://www.youtube.com/watch?v=NMNdBH0DQ64

    PS. Brad Dalton’s point about copying and pasting is important. It’s caught me out more than once.

  3. lucas says

    Hi Carrie,

    Not sure if this is the right place for this, but I wondered how create a testimonials widget like the one in your sidebar which (here’s the kicker) would randomly load a different testimonial each time the page reloads. I am going to create a testimonials CPT and can’t seem to get my head around how to approach a feature like this, though I *think* it would require some conditional coding…

    BTW I found your blog recently, and as a front-end designer taking the plunge into coding I must say that you really know how break down and explain things! Really helpful stuff all over. Thanks.

  4. says

    Hi Carrie

    I am having problems with conditional code to move the navigation bar under the content on the Home page – yet keep the nav bar at the top of the page for all other pages. I can’t seem to get this to work, the bar remains at the top – I have tried using page number in the conditional statement for the home page, if (is_page( 5 ) but that doesn’t work either

    Using Genesis in the Custom Code Custom Functions section.

    This is my code:

    <?php

    function move_navto_bottom () {
    if (is_front_page() ) {

    remove_action( 'genesis_before_header', 'genesis_do_nav' );
    add_action( 'genesis_after_content', 'genesis_do_nav' );
    }
    }

    Thanks for any ideas!
    Anne

    • says

      Carrie – figured it out:

      function move_navto_bottom() {
      if (is_front_page()) {
      /*move the nav bar below the content box*/
      remove_action(‘genesis_before_header’, ‘genesis_do_nav’);
      add_action(‘genesis_after_content’, ‘genesis_do_nav’);
      }
      else
      {
      /*move the nav bar above the content box*/
      remove_action(‘genesis_before_header’, ‘genesis_do_nav’);
      add_action(‘genesis_before_content’, ‘genesis_do_nav’);
      }
      }

      add_action(‘genesis_before’, ‘move_navto_bottom’);

      Thanks!