Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Widget preivew not working if widget registered via a instance #32781

Merged
merged 6 commits into from
Jun 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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