If I include a template part within header.php like this:

    <?php get_template_part('templates/social-icons'); ?>

Is there a way to retrieve the template name header.php within this template part? i.e the name of the template which is including social-icons.php?

So in social-icons.php I want to retrieve the name 'headers.php' dynamically so that I can include social-icons.php elsewhere and react to the name of the calling template.

perhaps something using PHP's get_included_files() or pathinfo() ?

1 Answer 1


After finding this answer, I went with:

$template_tree = mytheme_get_template_tree();
$total = count($template_tree); //count the elements in the array
end($template_tree); //set the pointer to the end of the array
$immediate_parent = basename(prev($template_tree)); //get the filename of the penultimate element

Then in a plugin / functions.php

function mytheme_get_template_tree()
    $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 ] );

    return $included_files;


Am still interested to hear about alternative approaches though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.