Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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!

share|improve this question
add comment

1 Answer 1

up vote 2 down vote accepted

$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 . ']';
}
share|improve this answer
    
when you say They are unique for each widget do you mean even if they are the same widget but because they are used multiple times they are unique? –  Lucky Luke Oct 18 '12 at 20:52
1  
Yes, the number is always unique. Read this answer to understand how WordPress creates widget instances. –  toscho Oct 18 '12 at 21:02
    
Thanks a lot for your time! –  Lucky Luke Oct 18 '12 at 21:50
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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