Get the Template File name in WordPress

WordPress theme by default uses number of template files to display content. These pages or files are generally known as theme files (page.php, single.php etc.). Even though you can always use number of conditional tags to figure out the pages or template files that your site is using at any given time, its always a good idea to grab the name of the template file and do certain conditional things based on the template files.

You can easily grab the file name using the following snippet.

<?php echo basename(get_page_template()); ?>

You can use this snippet to perform certain task whenever a conditions is met. Here is a sample of such snippet.

// hold the file name (i.e. page-contact.php)
$filename = basename(get_page_template()); 
if ($filename == 'page-contact.php') { 
   // do something if the condition is true
   echo 'Contact page template.';

What we are doing is, first of all grabbing the name of the template file and then checking it with an "if" condition to echo out certain words, if the condition is true. Obviously there are lots of ways you can be more creative wit this snippet but I am just giving you the idea how possibly you can do that. I hope that helps.

References: get_page_template


Commenting is disabled.