Include WordPress Template Files In Your Theme
It's common practice in PHP development to use template files to include in your web pages. WordPress comes with in-built functions to include certain files in your theme:
- get_header() - Includes the header.php file
- get_sidebar() - Includes the sidebar.php file
- get_footer() - Includes the footer.php file
If you want to include custom files in your WordPress theme you need an easy way to include these in your theme. You can use the PHP function include, but the problem with this is that you need to know the full path of the file. If you are looking for the full path of a file in your theme folder the path can be huge /root/wp-content/themes/twenty-twelve/include/new-file.php.
There is an easier way...Wordpress has a function to include files within the same theme folder.
This function is
get_template_part( $slug, $php );
How To Use get_template_part()
If I have a file which I am going to use to display the Author information at the end of the content I might want to use the same file on the Author page to keep a consistent style.
Therefore I would put the HTML needed into it's own custom-author.php file and might want to organise this into an includes folder in the theme.
Then after the content we can include the custom-author.php file by using the get_template_part function.
get_theme_file( 'includes/custom-author' );
Use PHP Constant
Wordpress creates a number of PHP constant variables which you can use in your theme, one of these constant variables is to get the theme path.
Having the theme path means you can include any file in your theme by using this constant variable and the default PHP include or require functions.
<?php include (TEMPLATEPATH . '/your-file.php'); ?>
Gain access to all tutorials
- Premium tutorials covering WordPress, Laravel and VueJS
- Download premium content
- Download premium WordPress plugins
- Only $5 a month
Join the weekly newsletter
Sign up for our newsletter. You'll be updated on new tutorials as they come available.