Making Conditional Tags Work Magic in Your WordPress Site

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:


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:

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:


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:


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?

 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;

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:

<?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:

<?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:

<?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:


<?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.

FREE EBOOK
Your step-by-step roadmap to a profitable web dev business. From landing more clients to scaling like crazy.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

FREE EBOOK
Plan, build, and launch your next WP site without a hitch. Our checklist makes the process easy and repeatable.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

Pretty simple…and pretty nice looking too

lifestyle1-624x170
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:

<?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


<?php if ( ! has_excerpt() ) {
echo '';
} else {
the_excerpt();
}

2. Determine when to show the excerpt or the content

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

<?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

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

5. Different header or footer based on category

<?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

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

6. Check if post is custom post type

<?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:



<?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

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

9. Load external files(CSS and Javascript)

<?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.

<?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.