0

I've got a few custom widgets in my site, which I'm targeting to specific tags.

There may be a case where there may be an overlap in widget targeting, and the desirable behaviour may be to only show the first of the widgets that match to that section or tag.

Therefore, when a match occurs and the widget is to be displayed, I need to set a variable to indicate to the other widgets that are in that 'set' not to display anything.

The obvious, but hacky, way to do this would be with a global variable, but this feels wrong. So I am hoping the Gods of Wordpress have a proper WP way to do it. Am I right?

1 Answer 1

1

Presumably, these are widgets that you are writing. If so, basic PHP class methods should do it-- set a static class property to hold your "overlap" data.

class Foo extends WP_Widget {
  static $overlap;

  /*constructs etc*/
  function __construct($id = 'twidg', $descr = 'Test Widget', $opts = array()) {
    $widget_opts = array();
    parent::__construct($id,$descr,$widget_opts);
    /*do stuff*/
  }

  function widget() {
    // set static::$overlap
    static::$overlap .= 'something-';
    echo 'test widget :: '.static::$overlap;
  }
}

You could even create a "parent" widget to handle the "overlap" logic for all of your "child" widgets. For that see:

5
  • ...But thank you for the help, using a static variable did the trick, though I couldn't make using a parent class work which may have given me more flexibility. Every time I gave it a shot, I ended up with the parent class appearing in WP's widget dialog, and the child class no where to be seen. The desirable behaviour would be for the parent class to be invisible to the user, and the child class being the one the WP admin user interacted with.
    – gravy
    Mar 18, 2014 at 15:12
  • Don't add the parent widget, just the children.
    – s_ha_dum
    Mar 18, 2014 at 15:21
  • As in, don't do register_widget on the parent?
    – gravy
    Mar 18, 2014 at 16:52
  • Yes, correct. You don't have to register the parent widget, just the derivatives-- the children.
    – s_ha_dum
    Mar 18, 2014 at 16:55
  • Yep, that's where I was going wrong. Thanks again for the help -- and apols for the half-finished comment - don't you just hate sites that bind to the return button :)
    – gravy
    Mar 18, 2014 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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