好吧,我在几个小时的不眠之夜后找到了它:
呼叫$this->get_field_id($key)
在Widget构造函数中是一个错误。必须在function form()
(可能是由于使用了一些全局变量*)
大多数痛苦来自于这样一个事实,即它没有将小部件保存在侧栏中。原因是,在数据库的开发过程中,一切都变得一团糟。Wordpress似乎期望id_base
以及数据库中实际创建的实例。如果您想要清晰的图片,请尝试更改id_base
新鲜的东西最后的工作代码:
class DW_Center_Address_Widget extends WP_Widget {
// I changed the id_base a couple of times
const ID = \'dwbn-center-address-3\';
var $formDefinition;
var $widgetArguments = [];
function __construct() {
//Constructor
$widget_ops = array(\'classname\' => self::ID, \'description\' => Connector::get_translation( \'Displays the address of a Center stored in the SSO.\' ) );
parent::__construct( self::ID, Connector::get_translation(\'DW Center Address\'), $widget_ops );
$this->formDefinition = [
// a title field makes the wordpress widget definetly more usefull, it will display this value in gray
[
\'type\' => \'text\',
\'key\' => Shortcodes::ATTR_TITLE,
\'label\' => __(\'Title\'), // just take the standard translation
\'value\' => \'\' // the default value
],
[
\'type\' => \'info\',
\'label\' => Connector::get_translation("Change Center data at the:") . \'<br/>\' . \'<a target="_blank" class="button" style="margin-top: 10px;" href="the.sso">\' . Connector::get_translation(\'SSO\') . \'</a>\'
],
[
\'type\' => \'text\',
\'key\' => Shortcodes::ATTR_SLUG,
\'label\' => Connector::get_translation(\'Center Slug or Id\'),
\'value\' => \'\' // the default value
]
];
foreach ($this->formDefinition as $def) {
if (array_key_exists(\'key\', $def)) {
$this->widgetArguments[$def[\'key\']] = array_key_exists(\'value\', $def) ? $def[\'value\'] : \'\';
}
}
}
/**
* @param array $args - holds context information
* @param array $instance - the actual parameters
*/
function widget($args, $instance) {
echo Shortcodes::dw_center($instance);
}
function update($new_instance, $old_instance) {
$instance = [];
foreach ($this->widgetArguments as $key => $val) {
$instance[ $key ] = trim(strip_tags($new_instance[ $key ]));
}
return $instance;
}
function form( $instance ) {
$instance = wp_parse_args( (array) $instance, $this->widgetArguments );
$form = [];
for ($i = 0; $i < count($this->formDefinition); $i++) {
$form[] = $this->formDefinition[$i];
if (array_key_exists(\'key\', $form[$i])) {
$key = $form[$i][\'key\'];
if (array_key_exists($key, $instance)) {
$form[$i][\'value\'] = $instance[$key];
}
// it is important, that this functions are called during runtime, otherwise the widget ids will not be correct
$form[$i][\'id\'] = $this->get_field_id($key);
$form[$i][\'name\'] = $this->get_field_name($key);
}
}
echo Template::render(\'admin/forms/widget_form.html.twig\', [
\'form\' => $form
]);
}
}
* 这是为什么不依赖全局名称空间的又一个例子——wordpress不会改变,但如果你构建了一个数百万人将使用的新系统,请尽量避免;)。