0

I can't get the data saved and retrived in the edit form, Whats is wrong with following code:

<?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;
    }
}
1
  • where do you call init? Jan 21 '18 at 15:25
1

The problem is here:

$instance['content'] = (!empty( $newInstance['content'])) ? $oldInstance['content'] : '';

This translates to:

if newinstance content is not empty and has something in it
    then use the old instance content
else if it is empty
    use ''

Should it not be using new instance instead of old?

For example, here's the example in the WP Codex docs:

/**
 * 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;
}

So your save function does work after all, it's just saving the old value, not the new value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.