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

(avery) #1

96 PART II • Designing and Developing WordPress Themes


UNDERSTANDING TEMPLATE FILES


A theme consists of template files, at least one style sheet, and possibly additional files such as
functions.php. There is some confusion about this at times because people refer to the theme
as a template. That’s wrong; a theme is a theme, which in effect is a folder (that needs to be
situated in the wp-content/themes/ directory to be used) containing several files, some of
which are template files.

Template files can be used in a wide variety of ways. Their exact use depends on what you put
in them, of course. You can make them behave in almost any way you want by changing the
loop or leaving it out altogether, and you can use template tags to generate a specific behavior.
Likewise, you can make pages a lot more dynamic by using conditional tags, and if you really
want to shake things up, you can always use plugins to extend WordPress beyond any of the
built-in functionality.

There are a few things you need to know upfront about template files. First, you need to know
which ones are necessary for the basic functionality. Second, you have to work out which
template file is used when. Third, you should figure out which template files are necessary for
what you want to achieve.

Suppose you want the home page to be the same as the index.php pages, except with an added
image or welcome text. Should you use a home.php template in addition to index.php? It would
be a lot more convenient to add an is_home() conditional tag in index.php to output the
additions on the front page only. The same goes for single posts: If there is not much difference
between single post view and the front page, you can use is_single() to alter the parts that
need to be different (not linking the post title, for example).

WHICH TEMPLATE FILE IS USED WHEN?
The following are the various template files and the uses of each:

◾ Home and front page: front-page.php takes precedence. If a static Page is set as the front
page, it will be used, then home.php, and finally index.php.
◾ Single posts: single-X.php where X is the post type (for example, single-book.php if the
post type is “book”), then single.php, and finally index.php.
◾ Pages: The selected Page template comes first, then page-X.php where X is the Page slug,
then page-Y.php where Y is the Page ID, then regular page.php, and finally index.php.
◾ Category archives: category-X.php where X is the category slug, then category-Y.php
where Y is the category ID, then category.php, archive.php, and finally index.php.
◾ Tag archives: tag-X.php where X is the tag slug, then tag-Y.php where Y is the tag ID,
then tag.php, archive.php, and finally index.php.
Free download pdf