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.

<?php 
// 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

Today In History

  •  
  •  

Comment

Leave a Reply

Note: Convet HTML, PHP, JavaScripts from Postable, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.