I’ve found this to display the current name of the file used in template:
function get_template_name () {
foreach ( debug_backtrace() as $called_file ) {
foreach ( $called_file as $index ) {
if ( !is_array($index[0]) AND strstr($index[0],'/themes/') AND !strstr($index[0],'footer.php') ) {
$template_file = $index[0] ;
}
}
}
$template_contents = file_get_contents($template_file) ;
preg_match_all("Template Name:(.*)\n)siU",$template_contents,$template_name);
$template_name = trim($template_name[1][0]);
if ( !$template_name ) { $template_name="(default)" ; }
$template_file = array_pop(explode('/themes/', basename($template_file)));
return $template_file . ' > '. $template_name ;
}
Source: get name of page template on a page
It works quite well, except that in the backend, in the template select box, I get this ugly extra entry:
Does anybody have any idea how to fix it? I don’t even know why this function is called in the backend. Is there a conditional function like is_frontend()
– maybe this would solve the problem?
You could set a global variable during the template_include
filter and then later check that global vairable to see which template has been included.
You naturally wouldn’t want the complete path along with the file, so i’d recommend truncating down to the filename using PHP’s basename
function.
Example code:
Two functions, one to set the global, one to call upon it.
add_filter( 'template_include', 'var_template_include', 1000 );
function var_template_include( $t ){
$GLOBALS['current_theme_template'] = basename($t);
return $t;
}
function get_current_template( $echo = false ) {
if( !isset( $GLOBALS['current_theme_template'] ) )
return false;
if( $echo )
echo $GLOBALS['current_theme_template'];
else
return $GLOBALS['current_theme_template'];
}
You can then call upon get_current_template
wherever you need it in the theme files, noting this naturally needs to occur after the template_include
action has fired(you won’t need to worry about this if the call is made inside a template file).
For page templates there is is_page_template()
, bearing in mind that will only help in the case of page templates(a far less catch all function).
Information on functions used or referenced above: