I’m creating a very simple widget with 3 inputs. but whenever I changed the details, it’s not getting saved. Below is my code. Please let me know if there any issue. Thanks.

class Simple_Twitter_Widget extends WP_Widget {
function __construct() {
    $params = [
        'description'=> 'Display latest tweets from your twitter account',
        'name'=> 'Simple Twiiter Widget'
        ];
    parent::__construct('Simple_Twitter_Widget', '', $params);
}

public function form( $instance ){
    $title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'My Twitter Widget', 'text_domain' );
    $username = ! empty( $instance['username'] ) ? $instance['username'] : esc_html__( 'johndoe', 'text_domain' );
    $tweet_count = ! empty( $instance['tweet_count'] ) ? $instance['tweet_count'] : esc_html__( 5, 'text_domain' );

    ?>

    <p>
        <label for="<?php echo $this->get_field_id('title');?>">Title : </label>
            <input class="widefat" id="<?php echo $this->get_field_id('title');?>" name="<?php $this->get_field_name('title'); ?>" value="<?php echo esc_attr( $title ); ?>" />
    </p>

    <p>
        <label for="<?php echo $this->get_field_id('username');?>">Username : </label>
            <input class="widefat" id="<?php echo $this->get_field_id('username');?>" name="<?php $this->get_field_name('username'); ?>" value="<?php echo esc_attr( $username ); ?>" />
    </p>

     <p>
        <label for="<?php echo $this->get_field_id('tweet_count');?>">Number of tweets : </label>
            <input type="number" min="1" max="10" class="widefat" style="width: 50px;" id="<?php echo $this->get_field_id('tweet_count');?>" name="<?php $this->get_field_name('tweet_count'); ?>" value="<?php echo esc_attr( $tweet_count ); ?>" />
    </p>
    <?php

}

public function widget($args, $instance){

}

function update( $new_instance, $old_instance ){
    $instance = array();
    $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
    $instance['username'] = ( ! empty( $new_instance['username'] ) ) ? strip_tags( $new_instance['username'] ) : '';
    $instance['tweet_count'] = ( ! empty( $new_instance['tweet_count'] ) ) ? strip_tags( $new_instance['tweet_count'] ) : '';

    return $instance;

}
}

function register_simple_twitter_widget(){
    register_widget('Simple_Twitter_Widget');
}

add_action('widgets_init', 'register_simple_twitter_widget');

Read more here: WordPress Widget Not Saving Data


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: