How to use control_callback when creating a widget via functions.php or plugin?

Actually the from fields only should be in the control_callback function , both form and handling so try this:

<?php
/*
Plugin Name: custom dashboard widget
Plugin URI: http://en.bainternet.info
Description: custom dashboard widget with control form
Version: 0.1
Author: bainternet
Author URI: http://en.bainternet.info
*/

//show widget
function custom_dashboard_widget_coach() {
    //get saved data
    if ( !$widget_options = get_option( 'my_dashboard_widget_options' ) )
        $widget_options = array();
    $saved_team = isset($widget_options['team'])? $widget_options['team'] : '';
        echo "
        <p><strong>Finalized Game</strong></p>
        <div class="team_class_wrap">
            <label>Class {$saved_team}</label>
        </div>
        ";
}

//configure and update widget
function custom_dashboard_widget_coach_handle(){
    //get saved data
    if ( !$widget_options = get_option( 'my_dashboard_widget_options' ) )
        $widget_options = array();

    //process update
    if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['my_dashboard_widget_options']) ) {
        //minor validation
            $widget_options['team'] = wp_kses($_POST['my_dashboard_widget_options']['team'],array() );
        //save update
                update_option( 'my_dashboard_widget_options', $widget_options );
        }

    //set defaults  
    if(!isset($widget_options['team']))
        $widget_options['team'] = ''; //you can set the default
        echo "
        <p><strong>Finalize Game</strong></p>
        <div class="team_class_wrap">
            <label>Class</label>
            <select name="my_dashboard_widget_options[team]" id='team'>
                <option value="5a" ".selected( $widget_options['team'], '5a', false ).">5A</option>
                <option value="4a" ".selected( $widget_options['team'], '4a', false ).">4A</option>
                <option value="3a" ".selected( $widget_options['team'], '3a', false ).">3A</option>
                <option value="2a" ".selected( $widget_options['team'], '2a', false ).">2A</option>
            </select>
        </div>
        ";
}

//register widget
function add_custom_dashboard_widget_coach() {
        wp_add_dashboard_widget('custom_dashboard_widget_coach', 'My Team', 'custom_dashboard_widget_coach', 'custom_dashboard_widget_coach_handle');
}
add_action('wp_dashboard_setup', 'add_custom_dashboard_widget_coach');

Which will give you: enter image description here

And once you click “configure” you get the form:enter image description here

And when you click submit the data would be saved and you will see this:enter image description here

Now in my example the data is stored in the options table as an array in a new row but you can use the dashboard_widget_options option for widget specific data (widget settings) or usermeta for user specific data.

Leave a Comment