Lately I find myself re-using these handy bits of code in many of my WordPress themes. They will help you identify the name of the current template file being used in the front-end or admin. If you’re interested in checking against the current theme template then you should check out the core is_page_template() function.
To get the name of the current theme template file name you need to intercept the template_include
filter and save a new PHP global variable that can be referenced anywhere.
To do this add the following function to your functions.php
file:
/**
* Define current template file
*
* Create a global variable with the name of the current
* theme template file being used.
*
* @param $template The full path to the current template
*/
function define_current_template( $template ) {
$GLOBALS['current_theme_template'] = basename($template);
return $template;
}
add_action('template_include', 'define_current_template', 1000);
Now that you have the global $current_theme_template
variable available you need a function that can display or return the variable.
/**
* Get Current Theme Template Filename
*
* Get's the name of the current theme template file being used
*
* @global $current_theme_template Defined using define_current_template()
* @param $echo Defines whether to return or print the template filename
* @return The name of the template filename, including .php
*/
function get_current_template( $echo = false ) {
if ( !isset( $GLOBALS['current_theme_template'] ) ) {
trigger_error( '$current_theme_template has not been defined yet', E_USER_WARNING );
return false;
}
if ( $echo ) {
echo $GLOBALS['current_theme_template'];
}
else {
return $GLOBALS['current_theme_template'];
}
}
That should do it, you can use get_current_template()
to check the template name in your theme. If you want to display the filename for any reason you can pass a true
value as a parameter.
If you want to display a specific item in the WordPress admin for a particular theme template you can get the template filename from the postmeta
table in WordPress like this:
$post_id = ( isset($_GET['post']) ) ? intval($_GET['post']) : intval($_POST['post_ID']);
$template_file = get_post_meta( $post_id, '_wp_page_template', TRUE );
This can be useful to display a metabox, or maybe additional Help API items, on specific page templates in a theme. I use it all the time.