Fixing “The called constructor method for WP_Widget is deprecated since version 4.3.0!” error on WordPress

308 0

This post is also available in: Português

Last week I was updating one of my old WordPress websites to the most recent release of the CMS, 5.6.2. I don’t remember what was the actual version of the WordPress used on the website, but it was very old, since the website had more than 10 years old!.

One thing I did, as a rule of thumb when doing this job was to turn on Debug Mode on wp-config.php, to check the compatibility between my theme/plugins and the most recent WordPress release. I was shocked to see dozens of errors on my homepage, most of them saying: “The called constructor method for WP_Widget is deprecated since version 4.3.0!”.  The error was somehwat clear, WordPress was complaining before something that was deprecated on version 4.3.0 and was still being usde on my theme.

It was easy to find the culpit: old WordPress versions used a “pseudo-constructor” which was not really a constructor but a generic function with the same name as the class itself. Maybe it was done that way because on that time the Object Oriented approach of PHP was not that good. But since on the recent versions of PHP we have full support to Object Oriented Development, a proper constructor is now being used on Widgets definition. So the solution was simple to replace that “pseudo-constructor” with the real constructor. So this code:

class My_Widget extends WP_Widget {

    function My_Widget() {
        $widget_ops = array('classname' => 'my-widget', 'description' => 'My Widget description.');

        $control_ops = array('id_base' => 'my-widget');

        $this->WP_Widget('my-widget', 'My Widget', $widget_ops, $control_ops);
    }

    function widget($args, $instance) {

Must be replaced with the following code:

class My_Widget extends WP_Widget {

    function __construct() {
        parent::__construct(
            'my-widget', // Base ID
            'My Widget', // Name
            array( 'description' => 'My Widget description.' ) // Args
        );
    }

    function widget($args, $instance) {

You have to change it on all Widget definitions on your Theme/Plugins. But, since this raises an E_USER_DEPRECATED error, your users will not show any new errors on the page, unless you enable Debug Mode, which you shouldn’t in a Production Environment.

(Visited 636 times, 1 visits today)

Elisio Leonardo

Elisio Leonardo is an experienced Web Developer, Solutions Architect, Digital Marketing Expert, and content producer with a passion for technology, artificial intelligence, web development, and entertainment. With nearly 15 years of writing engaging content on technology and entertainment, particularly Comic Book Movies, Elisio has become a trusted source of information in the digital landscape.