Metabox Tutorial – Create First Dashboard Widget

Share this Article

As wordpress dashboard widget is a small block that performs a specific function. In this tutorial we will see how to create a dashboard widget.

Using Dashboard Widget API we can add the widgets on the dashboard. 

wp_dashboard_setup is the action hook used for adding or removing dashboard widgets from WordPress.

The wp_add_dashboard_widget() function is used to add widget to the administration dashboard.

Syntax

Adds a new dashboard widget.

wp_add_dashboard_widget( string $widget_id, string $widget_name, callable $callback, callable $control_callback = null, array $callback_args = null, string $context = 'normal', string $priority = 'core' )

Parameters details

$widget_id

(string) (Required) Widget ID (used in the ‘id’ attribute for the widget).$widget_name

(string) (Required) Title of the widget.

$callback

(callable) (Required) Function that fills the widget with the desired content. The function should echo its output.

$control_callback

(callable) (Optional) Function that outputs controls for the widget.

Default value: null

$callback_args

(array) (Optional) Data that should be set as the $args property of the widget array (which is the second parameter passed to your callback).

Default value: null

$context

(string) (Optional) The context within the screen where the box should display. Accepts ‘normal’, ‘side’, ‘column3’, or ‘column4’.

Default value: ‘normal’

$priority

(string) (Optional) The priority within the context where the box should show. Accepts ‘high’, ‘core’, ‘default’, or ‘low’.

Default value: ‘core’

Example

/**
 * Add a new dashboard widget.
 */
function owt_add_dashboard_widgets()
{
    wp_add_dashboard_widget(
        'dashboard_widget', // widget id
        'My Dashboard Widget', // widget title
        'owt_dashboard_widget_function' // widget callback function
    );
}
add_action('wp_dashboard_setup', 'owt_add_dashboard_widgets');

/**
 * Output the contents of the dashboard widget
 */
function owt_dashboard_widget_function($post, $callback_args)
{
    esc_html_e("Hello Online Web Tutor, this is my first Dashboard Widget!", "textdomain");
}

Above code will add a dashboard widget. You can add this code into your custom plugin code or add inside activated theme functions.php file.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5