0

Suppose you have a widget that depends on a metabox being added to, say, your Posts. An easy way to do this is to simply add the add_meta_boxes action to your Widget's constructor and off you go. When that widget is registered with register_widget() function, your metaboxes are added and off you go.

The problem with this approach is that, well, if the user hasn't actually dragged that widget into one of his sidebars, we still add the metaboxes. And, if for some reason we register two different versions of this widget (say we extend the widget), then we're uselessly running the function twice.

wp_register_sidebar_widget is called when the widget is registered, but that means it runs regardless of whether the widget actually appears in a sidebar or not.

Is there a corresponding action that is run when a widget is actually loaded into a sidebar? So in other words an action that will only run for each widget that is actually added to a sidebar? Or do we have to dig through a list of widgets gotten through wp_get_sidebars_widgets()?

2
  • I don't know your full context, but I think showing parts of UI conditionally on something that goes on in entirely different part of admin is very confusing for user.
    – Rarst
    May 16, 2013 at 20:02
  • @Rarst, a valid point, and one I'll be sure to keep in mind. In this particular case, I think it makes complete sense to tie the metaboxes in the Edit Post page to the presence of the Widget.
    – Tom Auger
    May 17, 2013 at 15:00

1 Answer 1

0

I'm still eager to hear of an action that applies to this use case, but here's a more brute-force approach, if nothing else turns up:

// within My_Widget class definition
private static $metaboxes_added = false; // to ensure we don't add them more than once

// inside My_Widget class constructor
add_action( 'init', array( $this, 'add_metaboxes' ) );

// later, inside My_Widget class
public function add_metaboxes(){
    global $wp_registered_sidebars;

    if ( is_admin() && ! self::$metaboxes_added ){
        // These are the widgets grouped by sidebar
        $sidebars_widgets = wp_get_sidebars_widgets();

        foreach ( $sidebars_widgets as $sidebar_id => $widgets ) {
            if ( 'wp_inactive_widgets' == $sidebar_id )
                continue;

            if ( isset( $wp_registered_sidebars[ $sidebar_id ] ) ) {
                if ( in_array( $this->id, $widgets ) ){ // $this is our Widget
                    self::$metaboxes_added = true; // In case we instantiate this sucker twice

                    add_action( 'add_meta_boxes', array( $this, 'add_metabox_stuff' ) );

                    break; // No need to go any further
                }
            }
        }
    }
}

Your Answer

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

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