Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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)){
  //
}
share|improve this answer
    
Thanks for the help. This is pretty much as close as I was expecting, so I have no problem accepting is as correct. One quick note: According to the codex, the first parameter of locate_template() is an array. I needed the array anyway (I was using the second paramter of get_template_part() before), but I think you'd need it even for the single entry like in your example. –  mrwweb May 16 '12 at 21:58
    
not really, because whatever argument you give, it will be casted to array... –  onetrickpony May 16 '12 at 22:27
    
Ok. Thanks for the clarifications. –  mrwweb May 16 '12 at 22:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.