0

Following a tutorial and it works fine. I just can't understand how update method saves $instance array in the database from Select tag? You can choose default or full, slick save in the admin area and it saves in the db.

   public function widget( $args, $instance ) {
      echo $args['before_widget'];

          echo '<div class="g-ytsubscribe"       
              data-layout="'.$instance['data_layout'].'" 
              data-count="default">
            </div>';
      
      echo $args['after_widget'];
    }

    public function form( $instance ) {
      $data_layout = ! empty( $instance['data_layout'] ) ? $instance['data_layout'] : esc_html__( 'default', 'yts_domain' );
      ?>
      
      
      <select class="widefat" 
        <option value="default" <?php echo ($data_layout == 'default' ? 'selected' : ''); ?>>Default</option>
        <option value="full" <?php echo ($data_layout == 'full' ? 'selected' : ''); ?>>Full</option>
      </select>
      
      }
      
    public function update( $new_instance, $old_instance ) {
      $instance = array();

      $instance['data_layout'] = ( ! empty( $new_instance['data_layout'] ) ) ? sanitize_text_field( $new_instance['data_layout'] ) : '';

      return $instance;
    }
1
  • So my guess is that it looks at the form and collects values using their Ids. For example I have an input field and select field. It looks at whatever values are present at the time when you click Save, updates $instance array and calls update with new and old data. Commented May 12, 2021 at 18:38

1 Answer 1

0

When you create a widget you're extending the WP_Widget class:

class Foo_Widget extends WP_Widget {

The actual saving of the values in the database is handled by the parent class, in the update_callback() method.

So all your widget needs to do is tell it the new values, which you do by defining the update() method.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.