Skip to content

Instantly share code, notes, and snippets.

@Xtremefaith
Created December 3, 2013 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xtremefaith/7774321 to your computer and use it in GitHub Desktop.
Save Xtremefaith/7774321 to your computer and use it in GitHub Desktop.
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()
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment