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 
}

1 Answer 1

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

1
  • 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. Sep 13, 2016 at 10:03

Your Answer

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

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