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:

Leave a Comment