Get WordPress Template

Which WordPress template is in use?

A WordPress page can be configured to use one of the available page templates. This can be useful either for inclusions within the template or to generate a different feel for sections of the website.

However, the page header and footer are not governed in the same way as the page content. If you wish to tailor the header according to the template in use, perhaps a colour variation or a different banner image, then knowledge of the chosen template is required.

For example dependant upon the template, which is in use, a block of code can be shown. Perhaps only showing a slider header or featured image according to the template.

Such a function to control the content could be placed within the associated header or footer file. Accumulating such functions within the functions.php file can allow for a cleaner header or footer file. It allows for the use of reusable inclusion files, a file which may be deployed across multiple sites incorporating known functions.

Functions which have been created within the theme functions.php and included files, or within the header and page files can check which template is in use and action as appropriate.

A simple reference to get the page template in use is

get_page_template()

But this will return the whole template reference, for example:

/usr/share/wordpress/wp-content/themes/mytheme/page.php

To trim this and make the tests more generic use basename:

basename(get_page_template())

In the example above this trims down to:

page-commercial.php

You could test for a match which includes And to exclude the php extensions

get_page_template_slug maybe better

str_replace(".php","",get_page_template_slug())

Thus giving, from the previous example

page-commercial

It is now possible to wrap a block of code with an if statement checking to see whether the page template in use is page-commercial and if it is to show a slider:

if (str_replace(".php","",get_page_template_slug()) == 'page-commercial'){
  show_slider();
}

Getting the WordPress template can be useful to enable the tailoring of website content and/or styling according to which page template has been assigned to a page.

References

https://codex.wordpress.org/Function_Reference/get_page_template