【问题标题】:WordPress - WP_Widget : Fatal error: Uncaught ArgumentCountError: Too few arguments to function WP_Widget::__construct()WordPress - WP_Widget:致命错误:未捕获的 ArgumentCountError:函数 WP_Widget::__construct() 的参数太少
【发布时间】:2026-02-13 06:05:01
【问题描述】:

我是自定义 wordpress 小部件创建的新手,我正在尝试创建一个。我在wp-content> plugins> custom-widgets> my-custom-widget.php 创建了我的小部件。

这是我的代码

if(!class_exists("MyCustomWidget")){
    
    class MyCustomWidget extends WP_Widget{
       
        public function __constructor(){
            parent::WP_Widget(false,"My custom Widget");
        }
      
        public function form($instance){
            ?>
            <p>

            <label>Tilte:</label>
            <input type="text"/>
            
            </p>
            <?php

        }
    }
    
    function register_my_widget(){
        register_widget("MyCustomWidget");
    }
    
    add_action("widgets_init", "register_my_widget");
}

当我尝试激活它时,我得到了 wordpress 失败页面,特别是以下内容。怎么了?

Fatal error: Uncaught ArgumentCountError: Too few arguments to function WP_Widget::__construct(), 0 
passed in F:\Downloads\Worpress\Wordpress Local\apache2\htdocs\store\wordpress\wp-includes\class-wp-
widget-factory.php on line 61 and at least 2 expected in F:\Downloads\Worpress\Wordpress 
Local\apache2\htdocs\store\wordpress\wp-includes\class-wp-widget.php:162 Stack trace: #0 
F:\Downloads\Worpress\Wordpress Local\apache2\htdocs\store\wordpress\wp-includes\class-wp-widget-
factory.php(61): WP_Widget->__construct() #1 F:\Downloads\Worpress\Wordpress 
Local\apache2\htdocs\store\wordpress\wp-includes\widgets.php(115): WP_Widget_Factory->register() #2 
F:\Downloads\Worpress\Wordpress Local\apache2\htdocs\store\wordpress\wp-content\plugins\custom-widget\wp-
custom-widget.php(34): register_widget() #3 F:\Downloads\Worpress\Wordpress 
Local\apache2\htdocs\store\wordpress\wp-includes\class-wp-hook.php(287): register_my_widget() #4 
F:\Downloads\Worpress\Wordpress Local\apache2\htdocs\store\wordpress\wp-includes\class-wp-hook.php(311): 
WP in F:\Downloads\Worpress\Wordpress Local\apache2\htdocs\store\wordpress\wp-includes\class-wp-
widget.php on line 162

【问题讨论】:

    标签: php wordpress plugins widget


    【解决方案1】:

    有关完整正确的小部件示例,请参阅 this answer from wordpress.stackexchange.com

    这个问题的代码有几个问题:

    1. 这是function __construct() 而不是function __constructor()
    2. 正如富人的回答中所详述的,家长电话应该是parent::__construct(..)。例如:parent::__construct('', 'Widget name');

    【讨论】:

      【解决方案2】:

      在您的构造函数中,您需要传递 2 个参数...所以是这样的:

      public function __constructor(){
          parent::__construct('my_custom_widget',v__('My Custom Widget', 'my_text_domain'));
      }
      

      WordPress 文档在这里: https://developer.wordpress.org/reference/classes/wp_widget/__construct/

      【讨论】:

        最近更新 更多