diff --git a/src/wp-includes/widgets.php b/src/wp-includes/widgets.php index fbbdcf5f55..3b4944023c 100644 --- a/src/wp-includes/widgets.php +++ b/src/wp-includes/widgets.php @@ -1036,6 +1036,11 @@ function wp_convert_widget_settings($base_name, $option_name, $settings) { function the_widget( $widget, $instance = array(), $args = array() ) { global $wp_widget_factory; + if ( ! isset( $wp_widget_factory->widgets[ $widget ] ) ) { + _doing_it_wrong( __FUNCTION__, __( 'Widgets need to be registered before they can be displayed.' ), '4.9.0' ); + return; + } + $widget_obj = $wp_widget_factory->widgets[$widget]; if ( ! ( $widget_obj instanceof WP_Widget ) ) { return; diff --git a/tests/phpunit/tests/widgets.php b/tests/phpunit/tests/widgets.php index 233a7a8b02..83c1d3bcfa 100644 --- a/tests/phpunit/tests/widgets.php +++ b/tests/phpunit/tests/widgets.php @@ -678,6 +678,17 @@ class Tests_Widgets extends WP_UnitTestCase { } + /** + * Tests that no 'Undefined index' exception is thrown when trying to + * display an unregistered widget. + * + * @see \the_widget() + */ + function test_the_widget_with_unregistered_widget() { + $this->setExpectedIncorrectUsage( 'the_widget' ); + the_widget( 'Widget_Class' ); + } + /** * Register nav menu sidebars. *