我仍然渴望听到适用于此用例的操作,但如果没有其他结果,这里有一种更为暴力的方法:
// 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
}
}
}
}
}