Support » Plugins and Hacks » Widget forms

  • All of the examples for the new 2.8 widgets have a rather bad coding technique for the form function. They switch back and forth between PHP and HTML which won’t peform well and is difficult to spot errors.

    To save myself some effort I put together some helper functions.

    public function form_input_text($field,$caption,$value) {
         printf ('<p><label for="%s">%s: <input class="widefat" id="%s" name="%s" type="text" value="%s" " /></label></p>',$this->get_field_id($field),esc_html__($caption),$this->get_field_id($field),$this->get_field_name($field),esc_attr($value));
        public function form_input_option($field,$caption,$value,$options){
        foreach ($options as $option) {
            if ($option == $value) {$select = 'selected="selected"'; } else {$select = '';}
            $opthtml = sprintf('%s<option %s>%s</option>',$opthtml,$select,$option );
        printf('<p><label for="%s">%s:</label><select id="%s" name="%s" class="widefat" >%s</select></p>',$this->get_field_id($field),esc_html__($caption),$this->get_field_id($field),$this->get_field_name($field),$opthtml);
        public function form_input_checkbox($field,$caption,$value){
            if ($value) {
                $checked = 'checked="checked"';
                $checked= '';
            printf ('<p><input id="%s" class="checkbox" type="checkbox" name="%s" %s /><label for="%s"> %s</label></p>',$this->get_field_id($field),$this->get_field_name($field),$checked,$this->get_field_id($field),esc_html__($caption));

    Then your form code would become

        form_input_option('Option','Choose Option',$option,array ('Option 1','Option 2'));
        form_input_checkbox('Tick','Tick me',$checked);
  • The topic ‘Widget forms’ is closed to new replies.