Make WordPress Core


Ignore:
Timestamp:
04/29/2016 06:48:27 PM (9 years ago)
Author:
westonruter
Message:

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.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/class-wp-widget-factory.php

    r37063 r37329  
    5050     *
    5151     * @since 2.8.0
     52     * @since 4.6.0 The `$widget` param can also be an instance object of `WP_Widget` instead of just a `WP_Widget` subclass name.
    5253     * @access public
    5354     *
    54      * @param string $widget_class The name of a WP_Widget subclass.
     55     * @param string|WP_Widget $widget Either the name of a `WP_Widget` subclass or an instance of a `WP_Widget` subclass.
    5556     */
    56     public function register( $widget_class ) {
    57         $this->widgets[$widget_class] = new $widget_class();
     57    public function register( $widget ) {
     58        if ( $widget instanceof WP_Widget ) {
     59            $this->widgets[ spl_object_hash( $widget ) ] = $widget;
     60        } else {
     61            $this->widgets[ $widget ] = new $widget();
     62        }
    5863    }
    5964
     
    6267     *
    6368     * @since 2.8.0
     69     * @since 4.6.0 The `$widget` param can also be an instance object of `WP_Widget` instead of just a `WP_Widget` subclass name.
    6470     * @access public
    6571     *
    66      * @param string $widget_class The name of a WP_Widget subclass.
     72     * @param string|WP_Widget $widget Either the name of a `WP_Widget` subclass or an instance of a `WP_Widget` subclass.
    6773     */
    68     public function unregister( $widget_class ) {
    69         unset( $this->widgets[ $widget_class ] );
     74    public function unregister( $widget ) {
     75        if ( $widget instanceof WP_Widget ) {
     76            unset( $this->widgets[ spl_object_hash( $widget ) ] );
     77        } else {
     78            unset( $this->widgets[ $widget ] );
     79        }
    7080    }
    7181
Note: See TracChangeset for help on using the changeset viewer.