Is there a variable for a template parts name?

One you have called a template with get_template_part() (or locate_template()) is there a way to know what template you are in.

For example if you call get_template_part('loop','archive'); from archive.php

and then are working in your loop-archive.php file. is there a way to define a variable that has the name of the current template part…. so $template="loop-archive". better still, maybe in two parts so ‘loop’ and ‘archive’ but I can do that with some string splitting.

Question #10537 seems sort of related but doesn’t seem to cover template parts.

4 s
4

There isn’t a core global variable that returns the current context. However, you can construct your own, using contextual template conditional tags. You can step through the conditional tags in the same order as WordPress core, by following wp-includes/template-loader.php.

Simply wrap your output in a custom Theme function. Here’s how I do it (note: I don’t think I strictly follow template-loader.php):

function oenology_get_context() {

    $context="index";

    if ( is_home() ) {
        // Blog Posts Index
        $context="home";
        if ( is_front_page() ) {
            // Front Page
            $context="front-page";
        } 
    }else if ( is_date() ) {
        // Date Archive Index
        $context="date";
    } else if ( is_author() ) {
        // Author Archive Index
        $context="author";
    } else if ( is_category() ) {
        // Category Archive Index
        $context="category";
    } else if ( is_tag() ) {
        // Tag Archive Index
        $context="tag";
    } else if ( is_tax() ) {
        // Taxonomy Archive Index
        $context="taxonomy";
    } else if ( is_archive() ) {
        // Archive Index
        $context="archive";
    } else if ( is_search() ) {
        // Search Results Page
        $context="search";
    } else if ( is_404() ) {
        // Error 404 Page
        $context="404";
    } else if ( is_attachment() ) {
        // Attachment Page
        $context="attachment";
    } else if ( is_single() ) {
        // Single Blog Post
        $context="single";
    } else if ( is_page() ) {
        // Static Page
        $context="page";
    }

    return $context;
}

Then, I just pass oenology_get_context() as a parameter, e.g.:

get_template_part( 'loop', oenology_get_context() );

I think something along these lines would be a good candidate for core, though I’m not sure the best way to implement. I’d love to submit a patch, though.

Leave a Comment