我无法在编辑表单中获取保存和检索的数据,以下代码有什么问题:
<?php
namespace App\\Widgets;
class TextWidget extends \\WP_Widget
{
public function __construct()
{
$widgetOpts = array(
\'classname\' => \'widget_text\',
\'description\' => __(\'Um texto puro qualquer.\'),
\'customize_selective_refresh\' => true,
);
parent::__construct(\'custom_text\', __(\'Texto puro\'), $widgetOpts);
}
public static function init()
{
add_action(\'widgets_init\', function() {
register_widget(self::class);
});
}
public function widget($args, $instance)
{
echo esc_html__($instance[\'content\'], \'text_domain\');
}
public function form($instance)
{
$instance = wp_parse_args(
(array) $instance,
[\'content\' => \'\']
);
?>
<p>
<textarea
class="widefat"
id="<?php echo esc_attr($this->get_field_id(\'content\')); ?>"
name="<?php echo esc_attr($this->get_field_name(\'content\')); ?>"
type="text"
cols="30"
rows="10"
><?php echo esc_attr($instance[\'content\']); ?></textarea>
</p>
<?php
}
public function update($newInstance, $oldInstance)
{
$instance = array();
$instance[\'content\'] = (!empty( $newInstance[\'content\'])) ? $oldInstance[\'content\'] : \'\';
return $instance;
}
}
SO网友:Tom J Nowell
问题在于:
$instance[\'content\'] = (!empty( $newInstance[\'content\'])) ? $oldInstance[\'content\'] : \'\';
这意味着:
if newinstance content is not empty and has something in it
then use the old instance content
else if it is empty
use \'\'
它是否应该使用新实例而不是旧实例?
例如,以下是WP Codex文档中的示例:
/**
* Sanitize widget form values as they are saved.
*
* @see WP_Widget::update()
*
* @param array $new_instance Values just sent to be saved.
* @param array $old_instance Previously saved values from database.
*
* @return array Updated safe values to be saved.
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance[\'title\'] = ( ! empty( $new_instance[\'title\'] ) ) ? strip_tags( $new_instance[\'title\'] ) : \'\';
return $instance;
}
所以你的save函数确实起作用了,它只是保存旧值,而不是新值