Closest thing to an is_widget() tag?

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?

1 Answer
1

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:

$_located = locate_template('template-name', false, false);

$in_widget = true; // not global :D      

// load it;
// any variables you have here will also be available in your template 

if($_located)
  require $_located;

In your template:

if(isset($in_widget)){
  //
}

A different way, without using that context variable:

if(isset($this) && ($this instanceof YourWidgetClass)){
  //
}

Leave a Comment