5

first time with custom widget. I'm trying to create it this way:

<?php namespace App; class My_Widget extends \WP_Widget { function My_Widget() { $widget_ops = [ 'name' => 'My widget', 'description' => 'My description' ]; parent::__construct( 'My_Widget', 'My widget', $widget_ops ); } } function load_widget() { register_widget( 'App\\my_widget' ); } add_action( 'widgets_init', __NAMESPACE__ . '\\load_widget' ); 

And I get this error:

Too few arguments to function WP_Widget::__construct(), 0 passed in /srv/www/contraindicaciones.net/current/web/wp/wp-includes/class-wp-widget-factory.php on line 61 and at least 2 expected 

What am I doing wrong? Thanks!

1 Answer 1

12

You're using an extremely outdated method of creating a widget. You should be using the __construct() function, not a named function, as the constructor, as documented.

namespace App; class My_Widget extends \WP_Widget { function __construct() { $widget_ops = [ 'name' => 'My widget', 'description' => 'My description' ]; parent::__construct( 'My_Widget', 'My widget', $widget_ops ); } } function load_widget() { register_widget( 'App\\my_widget' ); } add_action( 'widgets_init', __NAMESPACE__ . '\\load_widget' ); 
4
  • Thanks! It works. Here in the codex remain the old method as an example: codex.wordpress.org/es:API_de_Widget#Desarrollando_Widgets. Commented Feb 21, 2021 at 14:50
  • 1
    Unfortunately it looks like the Spanish documentation on the codex is extremely out of date. Use developer.wordpress.org if you can (I couldn't figure out how to check if there's decent Spanish translations). Commented Feb 21, 2021 at 14:58
  • 1
    This is fantastic and resolved my setup- now up and running on PHP8. Many thanks! Commented Oct 16, 2021 at 21:34
  • My takeaway: 1. Do not copy the parent constructor's signature (i.e. ($id_base, $name, $widget_options = array(), $control_options = array())). 2. Use a constructor with no parameters (i.e. __construct()) but 3. call the parent's constructor with arguments (e.g. parent::__construct( 'My_Widget', 'My widget', ...). Commented Jan 30 at 12:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.