Skip to content

Commit

Permalink
Widget preivew not working if widget registered via a instance (#32781)
Browse files Browse the repository at this point in the history
  • Loading branch information
spacedmonkey authored and jorgefilipecosta committed Jun 22, 2021
1 parent 79c7d0e commit 55e1f89
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 10 deletions.
35 changes: 30 additions & 5 deletions lib/widgets-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 ];
}
}
11 changes: 6 additions & 5 deletions packages/widgets/src/blocks/legacy-widget/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 '';
}

Expand All @@ -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();
}

Expand Down

0 comments on commit 55e1f89

Please sign in to comment.