Get Current Page Template

Sometimes in Wordpress development you will need to display certain theme files, using the rewrite engine. For example using custom post types will use a file name single-{posttype}.php, but if you are having rewrite problems Wordpress might just be displaying the single.php file. If you have multiple post types which using similar styling it can be quite confusing on which theme file Wordpress is actually using. Add the below snippet into your functions.php file and it will return the current theme file Wordpress is using.


function define_current_theme_file( $template ) {
    $GLOBALS['current_theme_template'] = basename($template);
 
    return $template;
}
add_action('template_include', 'define_current_theme_file', 1000);

Now on your header.php file you just need to echo the global variable in this function.


echo $GLOBALS['current_theme_template'];

Check The Page Template

If you want to make sure you only add code when a certain page template is being used then you can check the current page template by using the WordPress function is_page_template(). This function takes one parameter this is the file of the page template, if the current page template matches this parameter then the function will return true.


if ( is_page_template('contact-form.php') ) {
	// Runs this code when the contact form page template is being used
} else {
	// Runs this code when another page template is being used
}

Checking The Page Meta Data

Another way of getting the page template that your currently using is to access the post meta data in the database which stores which template to use. If you are using a custom page template then when you save the page the template will be stored in the wp_postmeta table under the meta name **_wp_page_template **. To access this data you just need to use the function get_post_meta();

$template_file = get_post_meta( get_the_ID(), '_wp_page_template', TRUE );

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring