I have a custom widget with a WP_Query loop that’s using get_template_part()
to include some standard information that I also use in theme files. However, I need to make one small change to the widget’s output that differs from the template file I grab with get_template_part()
. I know I could copy the template file and modify it, but then I have to maintain two sets of that code. What I’d prefer is something like an is_widget()
check that I could use like:
if( !is_widget() ) {
// include an extra goody
}
I know there is no is_widget()
, but is there some other WordPress thing I can look for?
Well, if you insist using get_template_part, the only solution I see is to define a global variable in your widget’s widget() function, and set it to true or something.
After you call get_template_part in your widget, set this variable to false. Within your template check for that variable, and if it’s true, it means you are within the widget.
A better way is to use
locate_template
and do the inclusion yourself. That way you can control what variables are exposed in your template, so you can pass a normal variable to your template:In your template:
A different way, without using that context variable: