WordPress - WP_Widget:致命错误:未捕获的 ArgumentCountError:函数 WP_Widget::__construct() 的参数太少

问题描述 投票:0回答:3

我是自定义 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
3个回答
3
投票

请参阅 来自 wordpress.stackexchange.com 的答案,了解完整正确的小部件示例。

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

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

0
投票

我在将旧 WordPress 网站从 PHP 7.4 更新到 PHP 8.1 时遇到了 OP 的问题。

对我来说,解决方案是进入“外观”>“小部件”,对每个小部件区域中的内容进行细微更改并重新保存。

在此之前,我确保所有主题和插件都是最新的。

该网站现在可以在 PHP 8.1 上正常运行


-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/

© www.soinside.com 2019 - 2024. All rights reserved.