Conditional Tags
February 16th, 2010
Wordpress Conditional Tags are an extremely useful tool that may seem scary to the beginner, but are really quite simple.
Why use them?
- They aide in creating simpler themes with fewer template / style files
- Make your wordpress run faster as they can cut down on the number of files accessed
- Create an easy way to manage dynamic style elements
Where to use them
- index.php
- page.php
- header.php
- anything.php
How to use them
Probably the simplest and most common usage of conditional tags is for controlling whether a certain element (for example, a div tag) appears. As is often the case when I am building a website, I want something like an announcement box (for headline news, etc) to appear in the header area when a visitor is viewing the homepage, but to disappear when on any other page.
To accomplish this sort of task, structure your index.php, page.php, or anything.php like this:
1 2 3 4 5 | <?php if (is_front_page()); { ?> <div class="announcement"> Big News! </div> <?php } ?> |
The above code will create a div that only shows up when a visitor is on the front (home) page of your website.
If, perhaps, you’d rather the announcement div showed up on your contact page, which we will for the sake of this tutorial assume has a page ID # of 5, then use this code:
1 2 3 4 5 | <?php if (is_page('5')); { ?> <div class="announcement"> Big News! </div> <?php } ?> |
Controlling Style Sheets
Maybe you’d like to have a blue color scheme on the homepage, but a red theme on everything else. And then you’d also like to have a default style sheet for all other pages. Simply put the following code in your header.php.
1 2 3 4 5 | <?php if (is_front_page()); { ?> <link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/style-blue.css" type="text/css" media="screen" /> <?php } else { ?> <link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/style.css" type="text/css" media="screen" /> <?php } ?> |
This is just a quick intro to wordpress conditional tags. Watch out for Conditional Tags – Part 2.
Tags: cms, conditional tags, Wordpress
Posted in Tutorials, Wordpress, php | No Comments »





