12

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: enter image description here

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. :)

1

2 Answers 2

5

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.

2
  • Thank you! I'll check it out and give an answer if i work out how to solve this. If you or any one else find any more resources on this please do not hesitate to share it :) Commented Mar 3, 2013 at 12:28
  • 1
    Never got to try this out, however if any one manages to build something like this please post your solution bellow. :) Commented May 1, 2013 at 11:11
2

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.

<?php

class imp_image_slider extends WP_Widget
{
/**
 * imp_image_slider constructor.
 */
public function __construct()
{
    parent::__construct(false, $name = "Impulse Image Slider", array("description" => "Creates Slick Image Slider"));
}

/**
 * @see WP_Widget::widget
 *
 * @param array $args
 * @param array $instance
 */
public function widget($args, $instance)
{
// render widget in frontend
}


/**
 * @see WP_Widget::update
 *
 * @param array $newInstance
 * @param array $oldInstance
 *
 * @return array
 */
public function update($newInstance, $oldInstance)
{
    $instance = $oldInstance;
    $instance['images'] = array();
    $instance['urls'] = array();
    if (isset($newInstance['images'])) {
        foreach ($newInstance['images'] as $key => $value) {
            if (!empty(trim($value))) {
                $instance['images'][$key] = $value;
                $instance['urls'][$key] = $newInstance['urls'][$key];
            }
        }
    }

    return $instance;
}

/**
 * @see WP_Widget::form
 *
 * @param array $instance
 */
public function form($instance)
{
    $images = isset($instance['images']) ? $instance['images'] : array();
    $urls = isset($instance['urls']) ? $instance['urls'] : array();
    $images[] = '';
    $form = '';

    foreach ($images as $idx => $value) {
        $image = isset($images[$idx]) ? $images[$idx] : '';
        $url = isset($urls[$idx]) ? $urls[$idx] : '';
        $form .= '<p>'
            . '<label>Slides:</label>'
            . sprintf(
                '<input type="text" name="%1$s[%2$s]" value="%3$s" class="widefat" placeholder="Image ID">',
                $this->get_field_name('images'),
                $idx,
                esc_attr($image))
            . '</p>'
            . '<p>'
            . sprintf(
                '<input type="text" name="%1$s[%2$s]" value="%3$s" class="widefat" placeholder="Url">',
                $this->get_field_name('urls'),
                $idx,
                esc_attr($url))
            . '</p>';
    }

    echo $form;
}
}

add_action('widgets_init', create_function('', 'return register_widget("imp_image_slider");'));

?>
3
  • Hi, can you also add comments or some info as how it helps OP in addition to the code posted as code only answers are discouraged
    – bravokeyl
    Commented Aug 9, 2016 at 12:14
  • 1
    Hi, I just did. Hope it helps.
    – HKandulla
    Commented Aug 9, 2016 at 12:42
  • @HKandulla Thank you sooo much. You and your code is my life saver once again Thank you. Commented Aug 3, 2017 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.