Being self taught, my current knowledge of WordPress and php has come through adapting existing themes. Therefore, it’s easy to see why it’s easy to stumble across better ways of doing things the more you dive in to different themes.
There are many reasons for wanting to create extra templates within your theme, but for the sake of this post i’m going to assume that I want to show a slightly different version of header.php when I visit my ‘about’ page. Here’s how I would have gone about it before today…
- Duplicate an existing template page (for example: page.php) and rename it page-about.php
- Duplicate the existing header.php file and name it header-about.php
- Open up functions.php (from within your theme folder) and write a new function with the new file names:
function get_headerabout( $name = null ) {
do_action( 'get_header', $name );$templates = array();
if ( isset($name) )
$templates[] = "header-{$name}.php";
$templates[] = 'header-about.php';} - Then use a php include in your new template file (page-about.php) to call in the new header:
<?php get_headerabout(); ?>
A bit long-winded I think you’ll agree, but until now I had no idea there was an easier way…
Enter get_template_part
To make your template file go and get header-about.php in one line of code instead of the four steps above, simply enter:
<?php get_template_part( 'header', 'about' ); ?>
Simple.
Your experiences
Have you come across anything similar whilst working with WordPress? If so, let me know what it is and maybe you’ll be helping me out too!
