Making Conditional Tags Work Magic in Your WordPress Site

Conditional Tags are one of those things that you can leverage on your WordPress site whether you are an ace in coding or just have enough knowledge to install a plugin. It’s amazing what a simple piece of PHP can do for your WordPress site. They work well with BuddyPress too.

But before we begin we really should know what conditional tags are, and the simple answer to that question is that a conditional tag is basically a yes/no question. When you use them, they return either a True or False response, and that response determines what happens, based on your instructions.

Here is a simplified breakdown of what a conditional tag looks like:

1
2
3
if ( define a condition) {
// Then do stuff
};

What happens here is very straightforward. IF the condition specified In the parentheses ( ) is true, THEN do whatever is laid out in the curly brackets { }.

So say for example:

1
2
3
if ( it’s hot outside) {
echo ‘Have a cold drink’;
};

So in our example, if it is hot outside, then you should have a cold drink…sounds like decent advice…

Let’s reverse that!

Conversely, if the condition in the parentheses is not met, then the rest is ignored.

We can reverse that and make this work so that if a condition is not valid something happens simply by adding an “!” mark to the beginning of our condition like this:

1
2
3
if ( ! define a condition) {
// Then do stuff
};

So in this example, because the condition in the parentheses is not true, we want to do the stuff set out in the curly brackets.
Going back to our drink example we could do something like this:

1
2
3
if (! It’s hot outside){
echo ”have a warm beverage”;
};

At first glance, if you were to read that statement without your developers cap on, it might seem unusual to have a warm beverage when it’s hot outside, but that ‘!”  at the beginning turns everything around and the statement then makes sense.
So this works very well when you’re just checking for a single condition but what happens when you want to check multiple things and do something when one of the conditions is met?

Featured Plugin - WordPress Membership Site Plugin

If you're thinking about starting a paid, or just private, membership site then this is truly the plugin you've been looking for. Easy to use, massively configurable and ready to go out of the box!
Find out more

 Let me introduce you to the ELSEIF statement…

The ELSEIF statement is very similar to the ELSE statement and is actually an extension  that allows you to check multiple conditions and perform an action when one of the conditions is met. Here is what it looks like in theory;

1
2
3
4
5
if( original_condtition){
// Do something here
} elseif ( second_condtion){
//do this instead
};

Breaking that down, it simply states that if the first condition is true, then do as instructed. If the first condition isn’t true, move on to the second condition and if that’s true, perform that action instead. You can add as many elseif statements as you like and I’ll show you an example using multiple elseif statements with WordPress code in the next section.

Combining Statements

So it’s great that you can check a condition and then perform an action , but what happens when you want to check multiple statements? Say hello to your new friends AND and OR.

As an example lets show the same unique text at the beginning of the home page  but only if the home page has the id of 3:

1
2
3
4
5
<?php
if (is_home() AND is_page(3)):
echo 'Welcome to the home page. Glad you could make it';
endif;
?>

And if we want to make the condition true if either of the conditions are met:

1
2
3
4
5
<?php
if (is_home() OR is_page(3)):
echo 'Welcome to the home page. Glad you could make it';
endif;
?>

(Note: instead of AND, we could have used ‘&&’, and instead of OR we could have used ‘||’.)

List of Frequently used WordPress tags

1.    is_page()- applies a condition to a specific page, e.g. ” Contact”. You can use the ID, title,or slug/name.
is_page(’3′)  or is_page(‘Contact’)
2.    is_home()- applies a condition to the home page.
3.    is _category()- applies a condition to a specific category.e.g. “Football”. Same as the is_page() example, we can use ID, title or slug/name
is_category(‘football’)
4.    is_single()- applies a condition to single posts or attachments
5.    is_tag()- applies a condition to a tag archive page. Similar to a category archive page.
6.    is_author()- applies a condition to an author archive page
7.    is_archive()- applies a condition to archived pages
8.    is_404()- applies condition to an HTTP 404: Not Found error page
9.    is_main_site – is main site in a Multisite setup

WordPress Specific Example

Say you are building a site for a newspaper and they would like to display a different banner image for each section of the newspaper to help visitors identify which section they are currently reading. By using a simple set of conditional tags, you can easily accomplish this.

Our newspaper has four different sections we want to identify:

  • Lifestyle
  • Entertainment
  • Sports
  • And a subsection of Sports –Football

( it’s a small, but well-written newspaper)…

So in order to display a banner image that’s different for each section we need to do some code work in the header.php of our theme. Using a code editor, look for the line
<header id=”masthead” role=”banner”> as we will be working in this general area. Now depending on what theme you are using ( I used twentytwelve for this example) you will want to first remove the following code:
(Reminder, if you are doing this on a live site, you will want to create a child theme so that your changes don’t get overwritten when you do upgrades on the theme)

Remove this section, which is the default header image code:

1
2
3
4
<?php $header_image = get_header_image();
if ( ! empty( $header_image ) ) : ?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img src="<?php echo esc_url( $header_image ); ?>" class="header-image" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" /></a>
<?php endif; ?>

and replace it with this code:

1
2
3
4
5
6
7
8
9
<?php if(is_page('lifestyle')):?>
<img src="http://yourdomain.com/wp-content/uploads/2013/03/lifestyle1.jpg">
<?php elseif (is_page('sports')):?>
<img src="http://yourdomain.com /wp-content/uploads/2013/03/sports.jpg">
<?php elseif (is_page('entertainment')):?>
<img src="http://yourdomain.com /wp-content/uploads/2013/03/entertainment.jpg">
<?php elseif (is_category('football')):?>
<img src="http://yourdomain.com /wp-content/uploads/2013/03/football.jpg">
<?php endif;?>

While it may look intimidating, it really shouldn’t be as all we are doing is working our way down a list and when one of the conditions are met, ( in this case a specific page being displayed) a condition is met ( show the appropriate image). If the condition wasn’t met, it wasn’t the right page, then keep working down the list until it found the proper condition ( the proper page) and display the image indicated for that page.

Pretty simple…and pretty nice looking too

lifestyle1-624x170

Featured Plugin - WordPress Facebook Plugin

Would you like to add Facebook comments, registration, 'Like' buttons and autoposting to your WP site? Well, The Ultimate Facebook plugin has got that all covered!
Find out more

So what happens if you want to do something other than what we have shown here? All you need to do is replace the condition (is_page(‘pagename’)) with any of the conditional tags found here in the Codex.

Say for example you wanted to put the text ‘Exclusive Article’ at the top of every single post, then all you would need to do is:

1
2
3
4
5
<?php
if(is_single( )){
echo ‘Exclusive Article’;
};
?>

And voila, just like that every single post is now an Exclusive article!

More examples

Here are some real world examples you can play with and use:

1. Hide the Auto displayed excerpt and display your post’s excerpt

1
2
3
4
5
<?php if ( ! has_excerpt() ) {
echo '';
} else {
the_excerpt();
}

2. Determine when to show the excerpt or the content

1
2
3
4
5
6
if ( is_home() || is_single() ) {
the_content();
}
else {
the_excerpt();
}

3. Check to see if a featured image has been uploaded and if not, display a default image

1
2
3
4
5
<?php if(has_post_thumbnail()) {
the_post_thumbnail();
} else {?>
<img src="<?php bloginfo('template_directory');?>/images/img.png" alt="">
<?php }?>

4. Is User logged in

1
<?php if ( is_user_logged_in() ) {     echo 'Welcome, registered user!'; } else {     echo 'Welcome, visitor!'; } ?>

5. Different header or footer based on category

1
<?php if (is_category('Lifestyle')) { get_footer('lifestyle'); } else { get_footer(); } ?>

WordPress would then look for the file footer-lifestyle.php

Same idea for the header

1
<?php if (is_category('entertainment')) { get_header('entertainment'); } else { get_header(); } ?>

6. Check if post is custom post type

1
<?php if ( is_singular( 'recipes' ) ):       // This post is of the custom post type recipes.  // Add whatever you want to do here endif; ?>

7. Style a div differently based on page type

In most themes, that main “div” is styled the same way on EVERY single page of the theme. Maybe you want it styled one way for your homepage, but another for paged pages, single posts, archives, etc. What you do in this case is to write different classes in your stylesheet for each and call them something like “single”, “archive”, and “paged” – and then you code it like this:

1
2
3
4
5
6
<?php } elseif (is_page()) { ?> class="paged"
<?php } elseif (is_single()) ?> class="singlepage"
<?php } elsif (is_archive()) { ?> class="archivepage" <?php } ?> >
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php endwhile; ?>

8. Add a search form when 404 is used

1
<?php if ( is_404() ) {     // add your search form code here} ?>

9. Load external files(CSS and Javascript)

1
2
3
4
5
<?php  if ( is_page( 'contact' ) ) {   ?>
<link  rel='stylesheet' href='/contactstyle.css' type='text/css' media='all' />
<script  type='text/javascript' src=k'/jqueryform.js'></script>
<script  type='text/javascript' src='/spec_forms.js'></script>
<?php  } ?>

10. Perform a function on every page but the home page.

1
<?php if (! is_home()): { // whatever you want to do here }; ?>

There’s a plugin for that

So what if you don’t want to get your hands dirty with code? Does that mean you cant take advantage of conditional tags? Of course not, because as we all know…there’s a plugin for that…and I’m a fan of a plugin called ‘Widget Logic’

Widget Logic plugin automatically adds itself to every widget making it easy to customize content in sidebars.

This plugin lets you ( among other things) display custom content in your sidebar depending on specific parameters. Say for example, we wanted to display a short bio of every author when the site visitor viewed the author archive page. Instead of building a new page with custom sidebar content in each page we can simply use the Widget Logic plugin and let it do the bulk of the work for us.

After installing the plugin you’ll notice that all of your widgets now have a new section at the bottom called surprisingly ‘ Widget logic:’ This new section now allows me to determine under what conditions I want this widget displayed, simply by adding the appropriate conditional tag in the box.

Going back to our example of creating a bio in the sidebar for each author on our newspaper site, I could simply add an individual text widget containing the bio for each author in the appropriate side bar and inserting the tag is_author(ID) tag I can now make sure that the proper bio displays on the appropriate author archive page.

You can do this with any widget you want, not just text widgets, which opens up the door to a whole new world of customization for your sidebars!

In addition, there are other conditional plugins out there as well, such as one that will help you control conditional menus. So just have a look around if you aren’t comfortable with code.

Comments (12)

  1. This is a great article. I wish I had something like this back when I was started to learn about wordpress.

    It’s quite easy and explained in detail I think.

    Great job.

  2. I wanted to add the banner for each category/section but it seems to work only for Twenty Twelve not any other themes. How do I make it work without using TT theme. Thanks!

  3. Hi jed_barish, the actual code isn’t specific to any theme. Depending on your theme, you may need to dig around in the header.php to find the proper code to eliminate. Using your code examining tool of choice, you should be able to locate the appropriate code and replace it with the code above. Make sure your file path is correct as well, and you should be good.Like I said, the actual code for replacing the banner images isn’t specific to twentytwelve.

  4. Interesting approach used by Widget Logic, a plugin I wasn’t aware of! A couple of years ago, I had to use precisely something like that for a website that needed not only different widgets depending on the category/page it was, but also on the language (it was a multilingual site using WPML). Back then, I looked at Conditional Widgets but it wasn’t flexible enough. I got to use Dynamic Widgets instead (which fully supports WPML). Dynamic Widgets avoids typing in code, but… it has a daunting control panel, where you can set up so many different things that it quickly becomes completely confusing!

    I wish I had been aware of Widget Logic back then, it seems so much simple to use, and, since it allows you to type any kind of conditions, it doesn’t have the limitations of Conditional Widgets…

  5. Great article. Just wish I’d seen this before building my last buddypress site with conditional uri based headers. I can probably simplify them based on this though.

  6. You approached this from the server side, and after having just read Gwyneth Llewelyn’s article on running WordPress on Nginx, it makes me think differently.

    You can accomplish all of these same conditional statements using a single JavaScript file as well. Tapping in to the power of jQuery – and I would suggest switch() statements (where appropriate) for easier code management – you can let the browser client do most of the work.

  7. I want to define that posts written by author A are automatically assigned to category 1 (and other categories if they choose to proactively assign more categories), and that posts written by author B are automatically assigned to category 2 (and other categories if they choose to assign more categories).

    How do you advise going about this?

Participate