Class 'my_widget' not found in widget.php

I try to create an own Widget, but i got an error:
Fatal error: Class 'my_widget' not found in /wp-includes/widgets.php on line 591
Here is my code from init.php:

class my_widget extends \WP_Widget {}
function wpb_load_widget() {
    register_widget( 'my_widget' );
add_action( 'widgets_init', __NAMESPACE__ . '\\wpb_load_widget' );

add_action( 'widgets_init', __NAMESPACE__ . '\\wpb_load_widget' ); is correct, you’re passing the namespace.

class my_widget extends \WP_Widget is correct, you need to make sure PHP is looking for WP_Widget in the global namespace.

register_widget( 'my_widget' ); missing namespace

Thanks! I still need to be used to namespaces…

so what was the solution here? how did you add the missing namespace?


I just struggled to find this solution as well, so if anyone else finds this site while Googling, here is the answer:

Add this at the top of your custom lib document, e.g. extras.php:
use WP_Widget;

Create a widget using the template from the Wordpress Widget API.

Add namespaces in the end of the function, like this:
function register_foo_widget() { register_widget( __NAMESPACE__ . '\\Foo_Widget' ); } add_action('widgets_init', __NAMESPACE__ . '\\register_foo_widget');

I hope this can be a help to someone :wink: