THE PENDING DRAFT

WordPress Conditional Tags for Beginners

January 31, 2013

Not long ago i didn’t have any plan how conditional statements in WordPress Themes work. I used them, even quite often to be honest. But it was mostly hacked together from different code snippets or other themes and if something didn’t work the way i wanted it was a very tedious task to find out whats wrong because i just didn’t get it.

But in the end, it’s not that complicated as it may look. So, let me try to explain how they work in simple terms.

What’s a Conditional Tag?

A conditional statement checks for a certain “condition” and outputs something if this condition is true. For example you have a function which outputs something, but you only want it on the front-page, or you want to have a different output on the front-page than you have on other pages. You can also check for way more complicated stuff, but for the sake of sanity let’s stick to an easy example. Show something, but only on the front page.

Luckily, there are lots of predefined conditional statements provided by WordPress. We use ‘<?php is_home();’ which we wrap up in a simple if/else statement to check if we are on the home page.

<?php
    if (is_home() ) {
        // OUTPUT ON THE HOME PAGE
    } else {
        // OUTPUT ON ANY OTHER PAGE
    }
?>

Some conditionals work just like that (like is_home), others accept optional parameters (e.g. is_single) and some even require parameters in order to work.

To check if we are on a single Post, Attachment or Custom Post Type page (basically everything which uses the single.php Template) we can simply use:

<?php
    if (is_single() ) {
        // OUTPUT ON SINGLE POST PAGES
    } else {
        // OUTPUT ON ANY OTHER PAGE
    }
?>

But maybe we wanna target just the post titled “Our super special Post”, that’s possible too.

<?php
    if (is_single( 'Our super special Post' ) ) {
        // OUTPUT ON OUR SUPER SPECIAL POST PAGE
    } else {
        // OUTPUT ON ANY OTHER PAGE
    }
?>

Of course you can also use if/else/elseif to check multiple things at the same time. So, to finish this little introduction, let’s combine all of the above in one sentence:

<?php
    if (is_home() ) {
        // OUTPUT ON THE HOME PAGE
    } elseif (is_single( 'Our super special Post' ) ) {
        // OUTPUT ON OUR SUPER SPECIAL POST PAGE
    } elseif (is_single() ) {
        // OUTPUT ON ANY OTHER SINGLE POST PAGE
    } else {
        // OUTPUT ON ANY OTHER PAGE
    }
?>

As said before, there are plenty of conditionals ready to be used, browse the Conditionals in the WP Codex to find out how to use them or if they accept/require parameters etc. Once you understood how they work, you can do really cool stuff with them.

Use the comments, if you’ve got any questions or if i missed something.

Leave your comment