我是自定义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:DownloadsWorpressWordpress Localapache2htdocsstorewordpresswp-includesclass-wp-
widget-factory.php on line 61 and at least 2 expected in F:DownloadsWorpressWordpress
Localapache2htdocsstorewordpresswp-includesclass-wp-widget.php:162 Stack trace: #0
F:DownloadsWorpressWordpress Localapache2htdocsstorewordpresswp-includesclass-wp-widget-
factory.php(61): WP_Widget->__construct() #1 F:DownloadsWorpressWordpress
Localapache2htdocsstorewordpresswp-includeswidgets.php(115): WP_Widget_Factory->register() #2
F:DownloadsWorpressWordpress Localapache2htdocsstorewordpresswp-contentpluginscustom-widgetwp-
custom-widget.php(34): register_widget() #3 F:DownloadsWorpressWordpress
Localapache2htdocsstorewordpresswp-includesclass-wp-hook.php(287): register_my_widget() #4
F:DownloadsWorpressWordpress Localapache2htdocsstorewordpresswp-includesclass-wp-hook.php(311):
WP in F:DownloadsWorpressWordpress Localapache2htdocsstorewordpresswp-includesclass-wp-
widget.php on line 162
请参阅来自wordpress.stackexchange.com的答案,以获得完整的正确小部件示例。
这个问题中的代码有几个问题:- 是
function __construct()
,不是function __constructor()
。 - 在rich的回答中详细说明了父呼叫应该是
parent::__construct(..)
。例如:parent::__construct('', 'Widget name');
在你的构造函数中,你需要传递两个参数…像这样:
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/