Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

38 PART I • Getting Started with WordPress


site. You can check for that with the conditional tag is_category() and then output
another sidebar if appropriate. Whenever it is another page within the site, use the traditional
get_sidebar() include tag.

The following code will replace the get_sidebar() PHP snippet in the theme’s template
files wherever it matters, which probably means files such as index.php, category.php, and
single.php:

<?php
if ( is_category( 'very-special' ) ) {

get_sidebar( 'special' );
} else {
get_sidebar();
}
?>

Here you’re asking if the category is very-special, which is the category slug (used in
permalinks and such) in this case. You could have asked for the category ID or the category
name as well, and although an ID is pretty foolproof, the code is a lot easier to read if you use
the slug because it is nice-named, meaning that it can’t contain nasty special characters and
such. If the category is in fact the one with the very-special slug, use the include tag
get_sidebar('special'), where 'special' is a parameter indicating that you want
sidebar-special.php.

Should the category not be the one with the very-special slug, the code will move on to
the else clause and tell WordPress to use the normal get_sidebar() include tag, which
means that you’ll include sidebar.php.

This is all very simple stuff, but it clearly shows how conditional tags can be used to create
dynamic pages. You’ll do fun stuff with them later.

WHY IS THIS GREAT?
Conditional tags are a great way to get some rudimentary control over your theme. Because
you can ask WordPress where the visitor actually is, and under what circumstances, that
means you can react to it. Including a different sidebar is a simple example, but you could use
conditional tags far beyond that. Features such as loading different template parts depending
on where you are on the site means that you can cut down on the necessary amount of
template files — or just make your theme a tiny bit more dynamic. Combining conditional
tags with a simple if clause will get you a long way.
Free download pdf