Given that you work with WordPress, you will understand that some value is recurrent itself many periods, like the loop. The new in WordPress 3.0 has put loop value in into a loop.php file to make it separated, and when it’s needed, just include it into theme file. Why don’t we follow that? Separating a repeatitive code into a file is a good way to organize and manage code. It keeps your code cleaner, easier to read. All these files can be saved in a folder or a sub-folder to make a good structure. In WordPress, there are several ways to include a template file in the current folder, which we discuss in this article.
I’ve been using get_template_part() methods for a while, and see that is a good way to organize your code and theme files. Looking into my theme folder now, you can easily find the code I need and customize it without touching any other files. Many WordPress themes and frameforks use the same principle, too. And if you have not, just try.
This method is faster because it does the job as easy as possible. You can see all the other methods, including those based on it (and some additional code). But it has a small disadvantage of not automatically check if the file exists.
The first way to include a template file in the current file, of course, is built in PHP instructions: include and require:
include TEMPLATEPATH . 'template-name.php'; //or include(TEMPLATEPATH . 'template-name.php');
It only contains a PHP file in the current file without checking the existence of the file. You must pass the full path of files are included.
load_template(TEMPLATEPATH . '/template-name.php');
This not only allows us to retrieve the file path, but also (optional) to include this file, too.
$load is a Boolean parameter True if you want to include this file, false if you want to get the file path alone.
This function retrieves path to file without the use of extension. For example if you want to include template-name.php file that’s located in theme folder, you can use:
It also checks the parent of parent, if file exists. get_query_template (user) locate_template () in its code.
Note that get_query_template () simply returns the file path. And the argument is a string in a single row. This is different from locate_template () where we can retrieve the file path or include, and we can go from a list of files to search.
get_template_part() WordPress 3.0+
In WordPress 3.0+, there is a more powerful function to include the file:
This function will include file named “(slug)-(name).php”. $name is optional, and if it is empty, the include file named “(slugs).php” You can see this as the theme is Twenty Ten used the loop to include:
get_template_part('loop'); // general loop, file 'loop.php' get_template_part('loop', 'index'); // loop for index, file 'loop-index.php' get_template_part('loop', 'single'); // loop for single post, file 'loop-single.php'