1

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

5
    $sideBars = wp_get_sidebars_widgets ();
    $mySideBar = false;
    foreach ($sideBars as $sideBarName => $sideBar) {
      if (array_search ($this->id, $sideBar) !== false) {
        $mySideBar = $sideBarName;
        break;
      }
    }
1
  • Works a charm! Didn't think it was possible.
    – N2Mystic
    Commented Dec 5, 2012 at 22:38
2
$widgets = wp_get_sidebars_widgets();
if( in_array( $this->id, $widgets['home-header-widget'] ) ) { 
    echo 'Match';
}

This should work, but only if the user has already saved the widget and not when they first dragged it to the home-header-widget area.

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.