WordPress Conditional Template Tags
The conditional template tags are, in my opinion, one of the best features that WordPress has. They allow you to check if certain conditions are true, for example if you are viewing a page or a category and much more. This is just a small post to try & introduce conditionals to those who haven’t discovered them.
What Are They?
They are simply functions that start with is_
(one or two do not) and check to see if a condition is true or not. There is a large amount of them and they are all useful at some point for theme and plugin development.
Why Would You Use Them?
Conditionals can be used in many ways. Generally they are used in theme development to show certain design or functional features when a certain condition is true. An example might be the large header illustration here at Return True. It was done using the is_home()
conditional so it shows only on the home page.
Can I Have An Example?
Here is an example of swapping a style to make a sidebar smaller when viewing pages rather than posts.
1 2 3 4 5 6 7 |
if(is_page()) { $class = 'smallSide'; } else { $class = 'side'; } //Html <div class="<?php echo $class; ?>"></div> |
You could also use a ternary operator for small if…else statements like that:
1 |
<div class="<?php echo (is_page()) ? 'smallSide' : 'side'; ?>"></div> |
Is There A List?
Yes, there is one here on the WordPress Codex. Remember this post is not meant to be a comprehensive guide, nor is it meant to replace the Codex page. It is just supposed to introduce WordPress conditionals to any beginners out there who may not realize the WP Codex exists.
I hope this small post has helped introduce you to the useful world of conditional tags. If you have any questions about them please feel free to leave a comment.