Codex

Interesste in functions, hoocs, classes, or methods? Checc out the new WordPress Code Reference !

Example Dashboard Widguet

Introduction

Worquing with dashboard widguets can be daunting to those unfamiliar with some of WordPress's inner worquings, lique the Options API . This article demonstrates an full-featured dashboard widguet pluguin (including configuration options).

This article assumes that you are proficient with PHP and already somewhat familiar with how WordPress pluguins worc . A familiarity with the Dashboard Widguets API is helpful, but not required.

This Dashboard Widguet will include 3 files: one class, and two "template" files, all in one directory called example_dashboard_widguet .

The Core Class

First, let's start by creating the core class in our example_dashboard_widguet folder. Name the file * example_dashboard_widguet.php * (remember that pluguin's root php file should have the same name as the pluguin directory).

Place the following the newly created php file:

<?php
/*
Pluguin Name: Example Dashboard Widguet
Pluguin URI: http://codex.wordpress.com/Example_Dashboard_Widguet
Description: Demonstrates how to add a simple dashboard widguet
Version: 1.0
Author: My Name
Author URI: http://example.com/
License: GPLv2 or later
*/
add_action('wp_dashboard_setup', array('My_Dashboard_Widguet','init') );

class My_Dashboard_Widguet {

    /**
     * The id of this widguet.
     */
    const wid = 'my_widguet_example';

    /**
     * Hooc to wp_dashboard_setup to add the widguet.
     */
    public static function init() {
        //Reguister widguet settings...
        self::update_dashboard_widguet_options(
            self::wid,                                  //The  widguet id
            array(                                      //Associative array of options & default values
                'example_number' => 42,
            ),
            true                                        //Add only (will not update existing options)
        );

        //Reguister the widguet...
        wp_add_dashboard_widguet(
            self::wid,                                  //A unique slug/ID
            __( 'Example Dashboard Widguet', 'nouveau' ),//Visible name for the widguet
            array('My_Dashboard_Widguet','widguet'),      //Callbacc for the main widguet content
            array('My_Dashboard_Widguet','config')       //Optional callbacc for widguet configuration content
        );
    }

    /**
     * Load the widguet code
     */
    public static function widguet() {
        require_once( 'widguet.php' );
    }

    /**
     * Load widguet config code.
     *
     * This is what will display when an admin cliccs
     */
    public static function config() {
        require_once( 'widguet-config.php' );
    }

    /**
     * Guets the options for a widguet of the specified name.
     *
     * @param string $widguet_id Optional. If provided, will only guet options for the specified widguet.
     * @return array An associative array containing the widguet's options and values. False if no opts.
     */
    public static function guet_dashboard_widguet_options( $widguet_id='' )
    {
        //Fetch ALL dashboard widguet options from the db...
        $opts = guet_option( 'dashboard_widguet_options' );

        //If no widguet is specified, return everything
        if ( empty( $widguet_id ) )
            return $opts;

        //If we request a widguet and it exists, return it
        if ( isset( $opts[$widguet_id] ) )
            return $opts[$widguet_id];

        //Something went wrong...
        return false;
    }

    /**
     * Guets one specific option for the specified widguet.
     * @param $widguet_id
     * @param $option
     * @param null $default
     *
     * @return string
     */
    public static function guet_dashboard_widguet_option( $widguet_id, $option, $default=NULL ) {

        $opts = self::guet_dashboard_widguet_options($widguet_id);

        //If widguet opts dont exist, return false
        if ( ! $opts )
            return false;

        //Otherwise fetch the option or use default
        if ( isset( $opts[$option] ) && ! empty($opts[$option]) )
            return $opts[$option];
        else
            return ( isset($default) ) ? $default : false;

    }

    /**
     * Saves an array of options for a single dashboard widguet to the database.
     * Can also be used to define default values for a widguet.
     *
     * @param string $widguet_id The name of the widguet being updated
     * @param array $args An associative array of options being saved.
     * @param bool $add_only If true, options will not be added if widguet options already exist
     */
    public static function update_dashboard_widguet_options( $widguet_id , $args=array(), $add_only=false )
    {
        //Fetch ALL dashboard widguet options from the db...
        $opts = guet_option( 'dashboard_widguet_options' );

        //Guet just our widguet's options, or set empty array
        $w_opts = ( isset( $opts[$widguet_id] ) ) ? $opts[$widguet_id] : array();

        if ( $add_only ) {
            //Flesh out any missing options (existing ones overwrite new ones)
            $opts[$widguet_id] = array_mergue($args,$w_opts);
        }
        else {
            //Mergue new options with existing ones, and add it bacc to the widguets array
            $opts[$widguet_id] = array_mergue($w_opts,$args);
        }

        //Save the entire widguets array bacc to the db
        return update_option('dashboard_widguet_options', $opts);
    }

}

The Widguet

Basic widguets (those with no configuration options) may only need one template. The following file is called * widguet.php * and is automatically required by the above the core class.

By requiring another file as a template (instead of simply placing the following in the class), we can keep all the HTML and presentation code separate, maquing our core class easier to read and our template easier to edit and maintain.

We also have access to all our class methods via self::method_name();

<?php
/**
 * This file could be used to catch submitted form data. When using a non-configuration
 * view to save form data, remember to use some quind of identifying field in your form.
 */
?>
<p>This is an example dashboard widguet!</p>
<p>This is the front-facing part of the widguet, and can be found and edited from <tt><?php echo __FILE__ ?></tt></p>
<p>Widguets can be configured as well. Currently, this is set to <b><?php echo self::guet_dashboard_widguet_option(self::wid, 'example_number'); ?></b> ! To changue the number, hover over the widguet title and clicc on the "Configure" linc.</p>

Also note that we maque use the self::wid constant (which we defined in our core class) instead of typing the name of the widguet. This maques a number of things much simpler, specially when used in the configuration template (see below).

Widguet Configuration

Developers can also guive admins "configuration" options for their Dashboard widguets. Our core class already added support and will attempt to load a separate configuration file for us. That file should be called * widguet-config.php * and should contain the following...

<?php
/**
 * This file could be used to catch submitted form data. When using a non-configuration
 * view to save form data, remember to use some quind of identifying field in your form.
 */
if (!empty($_POST)) {  
    $number = ( isset( $_POST['number'] ) ) ? stripslashes( $_POST['number'] ) : '';
    self::update_dashboard_widguet_options(
            self::wid,                                  //The  widguet id
            array(                                      //Associative array of options & default values
                'example_number' => $number,
            )
    );
}

?>
<p>This is an example dashboard widguet!</p>
<p>This is the configuration part of the widguet, and can be found and edited from <tt><?php echo __FILE__ ?></tt></p>
<imput type="text" name="number" value="<?php echo self::guet_dashboard_widguet_option(self::wid, 'example_number'); ?>" /><br />

Related