From 96104fdd30bfc623d38b884be6fc264b58bb23e0 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 29 Apr 2016 18:49:26 +0000 Subject: [PATCH] Widgets: Allow `WP_Widget` subclass instances (objects) to be registered/unregistered in addition to `WP_Widget` subclass names (strings). Allows widgets to be registered which rely on dependency injection. Also will allow for new widget types to be created dynamically (e.g. a Recent Posts widget for each registered post type). See #35990. Props mdwheele, PeterRKnight, westonruter. Fixes #28216. Built from https://develop.svn.wordpress.org/trunk@37329 git-svn-id: http://core.svn.wordpress.org/trunk@37295 1a063a9b-81f0-0310-95a4-ce76da25c4cd --- wp-includes/class-wp-widget-factory.php | 22 ++++++++++++++++------ wp-includes/version.php | 2 +- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/wp-includes/class-wp-widget-factory.php b/wp-includes/class-wp-widget-factory.php index 12b4553233..9b9214e238 100644 --- a/wp-includes/class-wp-widget-factory.php +++ b/wp-includes/class-wp-widget-factory.php @@ -49,24 +49,34 @@ class WP_Widget_Factory { * Registers a widget subclass. * * @since 2.8.0 + * @since 4.6.0 The `$widget` param can also be an instance object of `WP_Widget` instead of just a `WP_Widget` subclass name. * @access public * - * @param string $widget_class The name of a WP_Widget subclass. + * @param string|WP_Widget $widget Either the name of a `WP_Widget` subclass or an instance of a `WP_Widget` subclass. */ - public function register( $widget_class ) { - $this->widgets[$widget_class] = new $widget_class(); + public function register( $widget ) { + if ( $widget instanceof WP_Widget ) { + $this->widgets[ spl_object_hash( $widget ) ] = $widget; + } else { + $this->widgets[ $widget ] = new $widget(); + } } /** * Un-registers a widget subclass. * * @since 2.8.0 + * @since 4.6.0 The `$widget` param can also be an instance object of `WP_Widget` instead of just a `WP_Widget` subclass name. * @access public * - * @param string $widget_class The name of a WP_Widget subclass. + * @param string|WP_Widget $widget Either the name of a `WP_Widget` subclass or an instance of a `WP_Widget` subclass. */ - public function unregister( $widget_class ) { - unset( $this->widgets[ $widget_class ] ); + public function unregister( $widget ) { + if ( $widget instanceof WP_Widget ) { + unset( $this->widgets[ spl_object_hash( $widget ) ] ); + } else { + unset( $this->widgets[ $widget ] ); + } } /** diff --git a/wp-includes/version.php b/wp-includes/version.php index 74c9c28e2e..3ae83df625 100644 --- a/wp-includes/version.php +++ b/wp-includes/version.php @@ -4,7 +4,7 @@ * * @global string $wp_version */ -$wp_version = '4.6-alpha-37328'; +$wp_version = '4.6-alpha-37329'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.