Created
December 3, 2013 18:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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