For organizational or reuse purposes, you will often separate components of your theme into separate files to be used in several different places.
Before getting started, you need to identify the pieces of output that will be reused throughout your theme, and separate them into different PHP files. You may wish to separate common post listing structures or advertisement blocks.
First, you should identify the piece of output that you wish to reuse and separate it into a new file. For this recipe, we'll say that you have a notice snippet that you may wish to include in several places. Place the following code in a new file called notice-snippet.php:
<div class="notice-snippet"> Thanks for visiting my site! </div>
After you've separated it, you need to decide where you want to display the snippet. Wherever you want to display the snippet, insert the following:
<?php include TEMPLATEPATH . '/notice-snippet.php'; ?>
You'll notice that your snippet is now shown in the template wherever you inserted the above statement.
The include
function does exactly what you would think it does: it includes the contents of the separate file wherever you use it. The important thing to remember about this example is the TEMPLATEPATH
constant used in the include
statement.
TEMPLATEPATH
is a constant defined by WordPress that holds the directory path to the directory that contains the template used to render output for the theme. You should use the TEMPLATEPATH
constant whenever you need to have PHP access files from your theme.
In addition to the TEMPLATEPATH
constant, WordPress provides a STYLESHEETPATH
constant. Generally, these two constants hold the same variable. However, if a child theme is active, then the STYLESHEETPATH
constant will contain the file system path to the style sheet in use, whereas the TEMPLATEPATH
constant will contain the file system path to the parent theme directory.