WordPress dashboard widgets API

Introduction to WordPress Dashboard Widgets API

WordPress dashboard widgets can enhance the user experience by either displaying a simple information to admin or perform a specific configuration task from the administration area of the site.

fig: WordPress dashboard widgets area

Functions and hooks to use

  • Action Hook: wp_dashboard_setup or wp_network_dashboard_setup
  • Function: wp_add_dashboard_widget
add_action( 'wp_dashboard_setup', 'prefix_add_dashboard_widget' );
// for multisite use the hook:
add_action( 'wp_network_dashboard_setup', 'prefix_add_dashboard_widget' );

Example:

add_action( 'wp_dashboard_setup', 'bt_add_dashboard_widget' );

function bt_add_dashboard_widget(){
    wp_add_dashboard_widget(
        'bt_demo_widget',
        __( 'Demo Widget', 'textdomain' ),
        'bt_demo_widget_callback',
        
    );
}

function bt_demo_widget_callback(){
    // for demo, I just displayed a text but you can display any thing you want like, form, links, image, ...
    echo __( 'Demo widget content', 'textdomain' );
}
fig: demo dashboard widget

Removing a dashboard widget

To remove a dashboard widget use: remove_metabox( ‘bt_demo_widget’, ‘dashboard’, ”);

Example:

add_action( 'wp_setup_dashboard', 'bt_dashboard_widget' );

function bt_dashboard_widget(){
    wp_add_dashboard_widget(
        'bt_demo_widget',
        __( 'Demo Widget', 'textdomain' ),
        'bt_demo_widget_callback'
    );
}

function bt_demo_widget_callback(){
    // process form here or use AJAX to submit it
    if( $_SERVER['REQUEST_METHOD'] == 'POST' ){
        print_r( $_POST );
    }
    // you can display a form (include nonce value as well).
    ?>
        <form action="<?php echo esc_url( admin_url() ); ?>" method="post">
            <input name="test" type="text" value="" />
            <p class="submit">
                <?php wp_nonce_field( 'bt-widget' ); ?>
                <?php submit_button( __( 'Save' ), 'primary', 'save', false, array( 'id' => 'save' ) ); ?>
                <br class="clear" />
            </p>
        </form>
    <?php
}

Note: when using AJAX for submitting form, you can skip checking if the method is post or get.

Reference: WordPress Dashboard Widgets API

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.