What is this instance variable doing in the Widgets class

The lack of documentation for the WP_Widget class is driving me mad. Here is what I have salvaged off the codex:

    public function form($instance){
        ?>

        <label for="<?php echo $this->get_field_id('title'); ?>">Title: 
        <input type="text" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo $instance['title']; ?>" id="<?php echo $this->get_field_id('title'); ?>" />
        </label>

        <?php
    }

What is this $instance variable? The docs say it is The settings for the particular instance of the widget. But then why isnt it just another property of $this. Why does $this->get_field_name('title') seem to know something about a title and suddenly when we want the goddamn title I have to start going into this instance variable. What am I missing here.

Can you explain me where the $title is held, what the hell the $instance is different from $this and why we are using the title to get the field name?

Thanks loads!

1 Answer
1

$instance holds the data stored for this widget instance as an array. You could use the same widget multiple times, and each would get different data.

get_field_name() and get_field_id() returns name/id attributes for that widget. They are unique for each widget, but do not depend on the data. That’s why they do not have to know anything about the $instance:

function get_field_name($field_name) {
    return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
}

Leave a Comment