Is there a variable for a template parts name?

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

tech