This widget is constructed incorrectly.
There are 2 elementary flaws right here:
- It’s creating an object utilizing
new
, which is inaccurate. It’s the duty of the Widgets API to create the thing, not you, WP will create an occasion of that class for every widget current, so if there are 5 HelloWidgets, then 5 objects shall be created by WordPress. - Widget registration ought to by no means occur contained in the widgets constructor. This can be a mistake and an error.
Due to this misbehaviour the widget breaks on newer variations of WordPress, however extra importantly it ought to by no means have labored to start with, that it was in a position to run with code constructed this manner is an accident/coincidence.
Fixing The Widget
First, take away the $hello_widget = new HelloWidget();
name, it’s incorrect and never how widgets are meant to work.
Second, take away the register_widget
name and hook from the constructor. It doesn’t belong there. It must occur outdoors the category.
The ultimate outcome ought to look just like this:
/**
* A Good day Widget
*/
class HelloWidget extends WP_Widget {
public operate __construct() {
mum or dad::__construct(
'hello-widget',
__( 'Good day Widget', 'yourtextdomain' )
);
}
... remainder of widgets features
}
// Inform WordPress about our widget
add_action(
'widgets_init',
operate() {
register_widget( 'HelloWidget' );
}
);
Additionally notice that I added a textdomain to the __
name, and the registration has been moved outdoors of the widget.
Ideally the category must be in a file by itself, which is then included by the file that calls add_action
. Defining issues and doing issues shouldn’t occur in the identical file ( it makes it unattainable to run assessments in isolation and introduces tighter coupling which is undesirable and makes debugging tougher ).