The widget form function has to be named form(). You may not rename it if you want the widget class to know what its purpose is. You also need to have an argument in there, which I'm calling $instance, which the class also expects. This is where the current widget settings are stored. This function needs to have all of the functionalities to create the form that users will see when adding the widget to a sidebar. Let's look at some abbreviated code and then explore what it's doing, as follows:
public function form($instance) { $instance = wp_parse_args((array) $instance, array('template' => '')); $current_taxonomy = $this->_get_current_taxonomy($instance); ?> <p> <label for="<?php echo $this->get_field_id('title'); ?>">Title</label> <input type="text" class="widefat" id="<?php echo $this- >get_field_id('title'); ?>" name="<?php echo $this- >get_field_name('title'); ?>" value="<?php if (isset($instance['title'])) {echo esc_attr($instance['title']);} ?>" /> </p> <p> <label for="<?php echo $this->get_field_id('taxonomy'); ?>">Taxonomy</label> <select class="widefat" id="<?php echo $this- >get_field_id('taxonomy'); ?>" name="<?php echo $this- >get_field_name('taxonomy'); ?>"> <?php foreach(get_object_taxonomies('post') as $taxonomy) : $tax = get_taxonomy($taxonomy); if(!$tax->show_tagcloud || empty($tax->labels->name)) continue; ?> <option value="<?php echo esc_attr($taxonomy) ?>" <?php selected($taxonomy, $current_taxonomy); ?>> <?php echo $tax->labels->name; ?></option> <?php endforeach; ?> </select> </p> <?php }
First, you use a WordPress function named wp_parse_args(), which creates an $instance array that your form will use. What's in it depends on what defaults you've set and what settings the user has already saved. Then, you create form fields. Note that for each form field, I make use of the built-in functions that will create unique names and IDs and input the existing values, as follows:
- $this->get-field_id() creates a unique ID based on the widget instance (remember, you can create more than one instance of this widget).
- $this->get_field_name() creates a unique name based on the widget instance.
- The $instance array is where you will find the current values for the widget, whether they are defaults or user-saved data.
All the other code in there is just regular PHP and HTML. Note that if you give the user the ability to set a title, name that field title, and WordPress will show it on the widget form when it's minimized. The widget form this will create will look like the following: