The use of PHP4 style constructors to create widgets in WordPress was officially deprecated in version 4.3. As a result, the following error notice will be displayed in your site if WP_DEBUG
constant in wp-config.php
is set to true.
Notice: The called constructor method for WP_Widget is deprecated since version 4.3.0! Use
__construct()
instead.
In this tutorial, I will show us how to replace the old PHP 4 constructor with PHP 5+ magic constructor method in your website’s widgets code.
And in doing so, the notice will be removed and the risk of your website being broken if you decides to upgrade your server to PHP 7 because of the error is eliminated (PHP4 constructor support in PHP7 is non-existent).
Fix
Say you have a widget class with the following PHP4 style constructor.
class my_widget extends WP_Widget {
// constructor
function my_widget() {
parent::WP_Widget(
false,
__( 'My Widget', 'my-widget' ),
array( 'description' => __( 'My sample widget', 'my-widget' ) ) );
}
// ...
}
Worse still:
class my_widget extends WP_Widget {
// constructor
function my_widget() {
$this->WP_Widget(
false,
__( 'My Widget', 'my-widget' ),
array( 'description' => __( 'My sample widget', 'my-widget' ) ) );
}
// ...
}
All you need do is replace the function my_widget
with function __construct
and parent::WP_Widget
or $this->WP_Widget
with parent::__construct
like so:
class my_widget extends WP_Widget {
// constructor
function __construct() {
parent::__construct(
false,
__( 'My Widget', 'my-widget' ),
array( 'description' => __( 'My sample widget', 'my-widget' ) ) );
}
// ...
}
La Fin!