Xtremefaith
12/3/2013 - 6:07 PM

This is a quick basic template for WordPress widget forms function. Passing an array through a loop that creates the fields. This can be exp

This is a quick basic template for WordPress widget forms function. Passing an array through a loop that creates the fields. This can be expanded to included columns, but that is not the intention of this gist. Currently only builds TEXT & SELECT fields

<?php
function form($instance){
  /** Merge with defaults */
  $instance = wp_parse_args( (array) $instance, $this->defaults );  //Only if you set defaults in constructor (i.e.- $this->defaults = array(); )
  extract ( $instance, EXTR_SKIP);
  
  //Create new fields by adding to this array
  $fields = array(
    'title'   => array(
      'label'       => __( 'Title', 'div' ),
      'type'        => 'text',
      'save'        => false,
      'value'       => $title,
      'requires'    => '',
    ),
    'posts_per_page'    => array(
      'label'       => __( 'How many post?', 'div' ),
      'type'        => 'text',
      'save'        => false,
      'value'       => $posts_per_page,
      'requires'    => '',
    ),
  );
    
  foreach( $fields as $field => $args ){
    #Switch by field type
    switch ($args['type']) {
      case 'text':
        echo '<p'. $style .'>
          <label for="'.$this->get_field_id($field).'"><strong>'.$args['label'].':</strong></label> 
          <input class="widefat '. $save .'" id="'.$this->get_field_id($field).'" name="'.$this->get_field_name($field).'" type="text" value="'.esc_attr($args['value']).'" />
        </p>';
        break;

      case 'select':
        echo '<p'. $style .'>
          <label for="'.$this->get_field_id($field).'"><strong>'.$args['label'].':</strong></label> 
          <select class="widefat '. $save .'" id="'.$this->get_field_id($field).'" name="'.$this->get_field_name($field).'">';
            foreach ($args['options'] as $name => $value) {
              echo '<option value="' . $value . '"', $args['value'] == $value ? ' selected="selected"' : '', '>', $name, '</option>'; 
            }
          echo '</select>
        </p>';
        break; 

      default:
        echo '<p>No field defined for '.$args['label'].' - '.$args['type'].'</p>';
        break;
    }
  }


} #END Form() 
?>