Wordpress - Get name of the current template file

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:

  • is_page_template()
  • add_filter()
  • basename()

apparently this is enough:

add_action('wp_head', 'show_template');
function show_template() {
    global $template;
    echo basename($template);
}

or just use it directly in template (I tend to echo in footer.php in HTML comment)

<?php global $template; echo basename($template); ?>

Between native WP functions like get_template_part() and PHP's native includes the most reliable way to see theme's files used is to fetch list of all included files and filter out whatever doesn't belong to theme (or themes when parent and child combination is used):

$included_files = get_included_files();
$stylesheet_dir = str_replace( '\\', '/', get_stylesheet_directory() );
$template_dir   = str_replace( '\\', '/', get_template_directory() );

foreach ( $included_files as $key => $path ) {

    $path   = str_replace( '\\', '/', $path );

    if ( false === strpos( $path, $stylesheet_dir ) && false === strpos( $path, $template_dir ) )
        unset( $included_files[$key] );
}

var_dump( $included_files );

Tags:

Templates