From 55e1f89d05b865f59cc5edf6943d8e1ec92f1ae4 Mon Sep 17 00:00:00 2001 From: Jonny Harris Date: Tue, 22 Jun 2021 01:02:58 +0100 Subject: [PATCH] Widget preivew not working if widget registered via a instance (#32781) --- lib/widgets-api.php | 35 ++++++++++++++++--- .../src/blocks/legacy-widget/index.php | 11 +++--- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/lib/widgets-api.php b/lib/widgets-api.php index cf626da1618dd..f89d34fa1d304 100644 --- a/lib/widgets-api.php +++ b/lib/widgets-api.php @@ -217,6 +217,32 @@ function gutenberg_get_widget_instance( $id ) { } } +if ( ! function_exists( 'gutenberg_get_widget_key' ) ) { + /** + * Returns the registered key for the given widget type. + * + * Belongs in WP_Widget_Factory when merged to Core. + * + * Can be removed when minimum WordPress version is 5.8. + * + * @since 10.3.0 + * + * @param string $id_base Widget type ID. + * @return string + */ + function gutenberg_get_widget_key( $id_base ) { + global $wp_widget_factory; + + foreach ( $wp_widget_factory->widgets as $key => $widget_object ) { + if ( $widget_object->id_base === $id_base ) { + return $key; + } + } + + return ''; + } +} + if ( ! function_exists( 'gutenberg_get_widget_object' ) ) { /** * Returns the registered WP_Widget object for the given widget type. @@ -233,12 +259,11 @@ function gutenberg_get_widget_instance( $id ) { function gutenberg_get_widget_object( $id_base ) { global $wp_widget_factory; - foreach ( $wp_widget_factory->widgets as $widget_object ) { - if ( $widget_object->id_base === $id_base ) { - return $widget_object; - } + $key = gutenberg_get_widget_key( $id_base ); + if ( ! $key ) { + return null; } - return null; + return $wp_widget_factory->widgets[ $key ]; } } diff --git a/packages/widgets/src/blocks/legacy-widget/index.php b/packages/widgets/src/blocks/legacy-widget/index.php index 69277342a17b9..e832c98c24da5 100644 --- a/packages/widgets/src/blocks/legacy-widget/index.php +++ b/packages/widgets/src/blocks/legacy-widget/index.php @@ -24,13 +24,14 @@ function render_block_core_legacy_widget( $attributes ) { return ''; } - if ( method_exists( $wp_widget_factory, 'get_widget_object' ) ) { - $widget_object = $wp_widget_factory->get_widget_object( $attributes['idBase'] ); + $id_base = $attributes['idBase']; + if ( method_exists( $wp_widget_factory, 'get_widget_key' ) ) { + $widget_key = $wp_widget_factory->get_widget_key( $id_base ); } else { - $widget_object = gutenberg_get_widget_object( $attributes['idBase'] ); + $widget_key = gutenberg_get_widget_key( $id_base ); } - if ( ! $widget_object ) { + if ( ! $widget_key ) { return ''; } @@ -45,7 +46,7 @@ function render_block_core_legacy_widget( $attributes ) { } ob_start(); - the_widget( get_class( $widget_object ), $instance ); + the_widget( $widget_key, $instance ); return ob_get_clean(); }