The basic functionality
WordPress renders the theme files using the template hierarchy. Depending on the content type, it will select the file to use to render the layout for that specific content. Looking at the visual overview of the selection process, WordPress will select the file found in your theme’s root folder, prioritizing from left to right ( on the graphic ).
So in other words, for the Site Front Page type it will look at front-page.php
first, then home.php
and finally index.php
. if no file is found.
That being said, if you want to change the look of your home page, you should create a front-page.php
file in your theme’s root folder and do your magical stuff there.
But what about if you want to override the template hierarchy?
Overriding the default template hierarchy
To achieve this, you will need to use a filter to bypass the predefined structure of things.
template_include
is your friend here.
Like any other filter, it’s really easy to use. Here’s a snippet of how to use it to modify the home page of a website for instance ( not using either front-page.php
or home.php
).
add_filter( 'template_include', 'bn_custom_template', 99 );
function bn_custom_template( $template ) {
if ( is_front_page() && is_home() ) {
return PATH_TO_YOUR_FILE . 'template-filename.php';
}
// Return the default template otherwise
return $template;
}
you could also use locate_template( array( 'my-custom-template-file.php' ) )
if your file resides in STYLESHEETPATH
, TEMPLATEPATH
or wp-includes/theme-compat
. WordPress will look for your my-custom-template-file.php
in these locations in that order.
Another Example
Now the function I wrote above is a bit redundant as you could just use the default front-page.php
to achieve the same thing without the need to write that function in your code.
But let’s say I want to use a slightly different home page for authenticated users. Now let’s modify that function to make that happen.
add_filter( 'template_include', 'bn_custom_logged_in_template', 99 );
function bn_custom_logged_in_template( $template ) {
// Bail if user is not logged in
if( ! is_user_logged_in() ) {
return $template;
}
// Show the special home page to logged in users
if ( is_front_page() && is_home() ) {
return PATH_TO_YOUR_FILE . 'logged_in-front-page.php';
}
}
Other use case
You can now modify that function to suit your specific need.
- Is it to display a template file for a custom post type?
- On a specific page?
- On a specific day of the month?
- And so on!
I hope the examples were clear, if you want another example, let me know in the comments below!
Rohit Sharma says
nice article for overide template.. thanks