How to determine which sidebar the widget has been added to, via widget admin?

In the script below, which resides in a custom widget, I’m trying to determine which sidebar area the widget has been added to because I want to alter the default text depending on which sidebar the user has added the widget to. This code should only execute on the admin side while editing the widget.

However, regardless of which sidebar the widget is placed in (my theme has 4 – main sidebar, header, footer and below content), it echoes the “match” string in all of them.

In this case, I only want the echo to fire, when the widget is inside the widgetized sidebar whose id is “home-header-widget”.

What’s wrong with the if/then?

function form( $instance ) {

    global $wp_registered_widgets, $wp_registered_sidebars;
    $sidebars_widgets = get_option('sidebars_widgets');
    if($sidebars_widgets["home-header-widget"]) echo 'Match';

    $instance = wp_parse_args( (array) $instance, array( 'title' => '', 'text' => '', 'hide_title' => '' ) );
    $title = format_to_edit($instance['title']);
    $text = format_to_edit($instance['text']);
        if($text==''){
        $text="hello world";
    }

2 Answers
2

    $sideBars = wp_get_sidebars_widgets ();
    $mySideBar = false;
    foreach ($sideBars as $sideBarName => $sideBar) {
      if (array_search ($this->id, $sideBar) !== false) {
        $mySideBar = $sideBarName;
        break;
      }
    }

Leave a Comment