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.
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):
Then, I just pass
oenology_get_context()
as a parameter, e.g.: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.
bit of a facepalm, because the answer is in pure PHP
If you look at the source code of
get_template_part
function, you’ll see:It creates an array of 2 template names:
{$slug}-{$name}.php
and{$slug}.php
and useload_template
to find the template file and include it (the 2nd parameter istrue
, which means include that file).You can mimic this function to return the template file path instead of include it, like:
Usage:
You can play more with
$template
to get what you want.List all conditionals that are
true
As all
is_*()
functions have their equivalent in a query variable (the functions are just wrappers), you can access them also another way: Get simply all that aretrue
.I wrote a ticket on core/trac that adds a function to list them all.
In the meanwhile you can use both listed functions as helper plugins that show you on which request which conditional is available. It will print a
var_dump()
below the footer (both admin & public) at theshutdown
hook.This way you can simply loop through them.
@scribu added his own function to the ticket (an interesting solution too).
 Â
Performance
I ran a performance test on each function in the middle of a template using
timer_start/*_stop();
. TO be fair, I renamed all functions to a one character namea/b/c()
.As you can see, Chips hard coded function is fastest, then goes mine and last is in this case scribus.
Update
If you know me, then you know my love for iterators for their elegance, clearness and their ability to hold only a single item in memory instead of of copy of a whole array while looping. So here’s a quick custom class that extends a
FilterIterator
, therefore needing only a single method reworked.It can be used quite easily. The
$it->current()
holds the value, while$it->key()
returns the conditional/property name.