3

I have several custom widgets that are installed as part of my theme. I'd like to execute conditional code inside each widget's admin panel (not the public side, I'm just interested in the admin panel inside function form($intance)), depending on which sidebar the widget is inserted into.

How can I obtain a reference to the current sidebar id which holds the widget, from within the widget's function form($instance) handler?

  • So, are you looking for the sidebar id while in the admin area or on the front-end? – scribu Aug 9 '11 at 20:14
  • In the admin area, inside my function form($instance){} branch – N2Mystic Aug 9 '11 at 20:30
2

If your sidebar has a name, you can retrieve the sidebar name using get_sidebar( $name )

inside the widget itself, try this:

global $wp_registered_widgets, $wp_registered_sidebars;
$sidebars_widgets = get_option('sidebars_widgets');
if($sidebars_widgets["sidebar-1"]) echo 'hooray';
  • My sidebar has a name and an ID, however, get_sidebar($name) returns nothing when called inside of function form($instance) – N2Mystic Aug 10 '11 at 14:01
  • sidebar name refers to custom sidebar template, for example: sidebar-right.php – Sean Lee Aug 10 '11 at 19:58
  • Sean, this is inside the widget admin area, not on the public site. – N2Mystic Aug 11 '11 at 18:41
  • just added the snippet you can use inside the widget itself. That should work for admin area. – Sean Lee Aug 14 '11 at 3:17
  • Sean, should "sidebar-1" be the "name" or the "id" of the widget. Name never echoes, but using sidebar-id, I get echo on all instances of the widget, whether in the sidebar represented by the sidebar-id or not. – N2Mystic Aug 17 '11 at 21:41
3

If your widgets use the widget API you should have the following method in your widget class...

function widget($args, $instance){
    //output html here...
}

$args['id'] will hold the id of the current sidebar.

  • I'm trying to execute code inside the widget admin panel, not on the public side view. The function is function form($instance) so I do not have access to the $args in this context. – N2Mystic Aug 10 '11 at 13:59
  • Yeah, sorry -- I missed that comment. – Chris Carson Aug 10 '11 at 14:16
1

I'm afraid there's no easy way of doing that as of WP 3.2. In general, the widgets admin screen isn't very extensible.

You'll just have to make two widget classes and instruct users where to put each.

  • Ouch, say it aint so, Joe. – N2Mystic Aug 10 '11 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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