I am trying to add form field to a WordPress widget dynamically. So if the user want to add another date to an event they can click a button to get more fields.
The question is: How do save newly created input fields to my database?
Do i need to write a custom update function? Any tips?
This is how the widget looks:
This is my php code for the widget (so far):
class Spillelister extends WP_Widget {
public function Spillelister() {
$widget_options = array (
'classname' => 'spillelister-widget',
'description' => 'Widget for å illustrere spillelister.');
parent::WP_Widget('spillelister_widget', 'Spilleplan', $widget_options);
}
// The actual widget user interface
public function widget($args, $instance) {
extract( $args, EXTR_SKIP);
$title = ( $instance['title'] ) ? $instance['title'] : 'Spilleplan';
$body = ( $instance['body'] ) ? $instance['body'] : 'Ingen flere forestillinger';
?>
<?php echo $before_widget; ?>
<?php echo $before_title . $title . $after_title; ?>
<p><?php echo $body; ?></p>
<?php
}
public function update() {
}
public function form() {
?>
<div class="date_stamp">
<p>
<label>Dato</label> <input type="text" class="datepicker">
<br>
<label>Tid</label> <input type="text">
<span class="remove">Remove</span>
</p>
</div>
<p>
<span class="add">Add fields</span>
</p>
<?php
}
}
function spillelister_init() {
register_widget('Spillelister');
}
add_action('widgets_init', 'Spillelister_init');
Any tips, hints or answers are appreciated. 🙂
Interesting Question!
I’ve never seen repeatable fields used in Widgets. Giving a full Answer would require too much work/time, so I’ll give you links to the resources I know, and hopefully you’ll make this work and share the solution with us 😉
All this examples deal with Meta Boxes, you’ll need to copy the jQuery scripts and adapt the
post_meta
to the Widgets case.Create more Meta Boxes as needed – WPSE Q&A
Repeatable Custom Fields in a Metabox – Gist
Repeatable Custom Fields in a Metabox – Another Gist example, no description given. This one is quite interesting as it has the code to sort the fields.
This is an example of a dynamic widget that renders two fields (image-id and url). if you enter an image-id and press “update”, two new fields are added. I build it to create a slick slilder with images and linked url’s.