Understanding conditionals is an absolute must in creating unique WordPress sites. Like its name suggests the conditional tag allows you to display content depending on a specific condition.

The best place to start when learning how conditionals can be used is with page settings.

For example if you wanted to post a message of your home page or display a specific image, the following code would be added to your template file:

<?php if(is_front_page()) {?>
	<p>This is our front page so we will do this.</p>
	<?php } else {?>
	<p>We're no longer on the front page, so we will do that instead.</p>
<?php } ?>

Display different content on your sidebar

Conditional tags also allow you to dress up your sidebar differently depending on where you are on your site. I find myself building lots of websites for clients who do not wish to modify their first level of navigation, but do have the need to modify subpages. Thus with the parent page in place, I use the following code in my sidebar to create the sidebar navigation for each section.

<ul>
<?php if(is_page(2) || $post->post_parent==2) {
	wp_list_pages('sort_column=menu_order&amp;child_of=2&amp;depth=1&amp;title_li=');
	} elseif (is_page(3) || $post->post_parent==3) {
	wp_list_pages('sort_column=menu_order&amp;child_of=3&amp;depth=1&amp;title_li=');
	} elseif (is_page(4) || $post->post_parent==4) {
	wp_list_pages('sort_column=menu_order&amp;child_of=4&amp;depth=1&amp;title_li=');
	} elseif (!is_page()) {
	wp_list_categories('title_li=');
	}?>
</ul>

The page(#) correspond to the page ID. You could also use the slug if you prefer, but don’t forget to use single quotes.

Check to see if custom field exists

Conditional tags can also be used to check for things other than being a certain page. Testing to see if a custom field exist for example can be handy:

<?php while (have_posts()) : the_post();
	$link=get_post_meta($post->ID, 'link', true);
		if($link != '') {
 		echo '<a href="'.$link.'">';
 		echo the_post_thumbnail().'</a>';
		}else {
 		the_post_thumbnail();
		}
the_content();
endwhile; ?>

A similar example would be to check to see if a featured image has been uploaded and if not display a default one.

<?php if(has_post_thumbnail()) {
 	the_post_thumbnail();
	} else {?>
 	<img src="<?php bloginfo('template_directory');?>/images/banner.gif" alt="">
<?php }?>

As you can see conditional tags are very handy. The examples above are some of my most used code snippets. Do you have any favourites?