Dashboard Widgets

Creating new Dashboard widgets is not quite as elegant as creating sidebar widgets. For a very basic Dashboard widget, you'll have two essential functions, the widget itself (dashboard_notepad_widget()) and the setup function (dashboard_notepad_widget_setup()). Here, since the code for setting option defaults is used in both those functions, it has been pulled out into its own function, dashboard_notepad_widget_options(). Finally, you use the add_action() function to add your new widget to the Dashboard setup process using the wp_dashboard_setup() hook.

My Dashboard Notepad plugin creates an extremely simple Dashboard widget. Anything you enter into the form is saved there until you clear it out. It's great for jotting down ideas for future posts or sharing reminders with other site administrators. In this simplified version, it really has just one option: the note text.

The Dashboard Notepad widget is shown in Figure 8-5, and the source code is given in Listing 8-13. Take a look at the code, and then I'll walk through each piece.

Figure 8-5. The Dashboard Notepad widget

Listing 8-13. The Dashboard Notepad widget source code function dashboard_notepad_widget() {

$options = dashboard_notepad_widget_options(); if (!empty($_POST['dashboard_notepad_submit']) ) {

$options['notes'] = stripslashes($_POST['dashboard_notepad']);

update_option('dashboard_notepad', $options);

$dashboard_notepad = htmlspecialchars($options['notes'], ENT_OUOTES); $form = '<form method="post" action="'.$_SERVER['PHP_SELF'].'">';

$form .= '<textarea id="dashboard_notepad" name="dashboard_notepad" style="width: 95%; height: 12em; background: #fcfcfc;"';

$form .= '>'. $options['notes'].'</textarea>';

$form .= '<p><input type="submit" value="Save Notes" class="button widget-control-save"></p>

<input type="hidden" name="dashboard_notepad_submit" value="true" />'; $form .= '</form>'; echo $form;

function dashboard_notepad_widget_setup() {

$options = dashboard_notepad_widget_options();

if (!is_array($options)) $options = array('notepad_title' => 'Notepad'); wp_add_dashboard_widget( 'dashboard_notepad_widget_id', $options['notepad_title'],

'dashboard_notepad_widget'); }

function dashboard_notepad_widget_options() {

$defaults = array( 'notes' => 'Enter here whatever is on your mind.', 'notepad_title' => 'Notepad');

$options = get_option('dashboard_notepad'); if (!is_array($options)) $options = array(); return array_merge( $defaults, $options );

add_action('wp_dashboard_setup', 'dashboard_notepad_widget_setup');

■ Caution: The example in Listing 8-13 has been vastly simplified for the purposes of demonstration. The full plugin version includes a number of additional checks on users' permissions, such as whether they're allowed to post unfiltered HTML. Do not use the simplified code on a live site; download the plugin instead.

0 0

Post a comment