WordPress PHP Templates?
When creating different templates in WordPress try using conditionals instead of creating a whole new template. Within your header or even your template body you can use the following code to display different things for different pages.
<?php
if (is_page( 'home' ) {
?>
//html and php code here
<?php
} else {
?>
//html and php code here
<?php
}
?>
Templates are great but this can help you cut down on having a different template for every page.
Some things I use this for:
Displaying a different banner on every page
Altering the content div to display 100% on certain pages
Changing the background on different pages
Display multiple post types in the same template.
Written by Craig Bauer
Related protips
4 Responses
Good tip. I'll leave this link here for anyone looking for the full list of available conditional tags in WordPress since there are a lot of things you can do with them:
Thanks for adding that.
Thanks for this!
That's a double-edged sword. Yes it will be easy for you to navigate through the conditional blocks, but it will be more difficult for the less-tech-savvy admin of a site that uses your theme to figure-out what he has to tweak in order to add/remove something somewhere.
That's why some people recommend to use as much of get_template_part() as possible instead.
Use action hooks as well. Use an action that fires before the content of a page for instance. Then use add_action() in your theme's functions.php file in order to run any logic checks and once you figure out what has to be included just use get_template_part(). If you have a lot of secondary templates, put them in a well-organized directory structure(like /template-parts/header/, /template-parts/footer/, /template-parts/content/, etc. ) that will make it easier to navigate through.
This way you can end-up with a bunch of 10-line templates but it will be dead-easy to go in and add a new element to them.