3

I'm attempting to create my first ever widget and was hoping someone could explain the difference between $this and $instance used in the following widget form code.

<?php
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 
}
2

$this is the widget object, an instance of the relevant widget class. It includes things like the widget ID and class identifiers which are required for the method that generate the input id and name attribute in the snippet

$instance is the array which includes the widget setting. The settings ae not stored as part of the object and therefor needs to be passed as a parameter

  • you are welcome, this is just another example of core developer not understanding OOP concepts :( in one of my plugins I just add the $instance to the object as an instance field, not only to make it more logical but also because sometimes if the front end needs to use a filter it is easier to just add a method for that without having to pass the $instance as some global. – Mark Kaplun Sep 13 '16 at 10:03

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.