wp_add_dashboard_widget()WP 2.7.0

Adds (register) a new widget (a meta box) to the administration dashboard (the main page of the admin panel).

The function should be called during the following actions:

It means that WordPress uses following events to run widgets created (registered) by this function:

do_action( 'wp_dashboard_setup' );         // консоль
do_action( 'wp_network_dashboard_setup' ); // консоль сети сайтов
do_action( 'wp_user_dashboard_widgets' );  // консоль юзера

No Hooks.

Return

null. Nothing (null).

Usage

wp_add_dashboard_widget( $widget_id, $widget_name, $callback, $control_callback, $callback_args );
$widget_id(string) (required)
Widget ID. Will be used in the CSS class of the widget HTML block. Will be the key of the widget in the widgets array.
$widget_name(string) (required)
Title of the widget. Will be on the top of the widget, e.g. "Latest comments".
$callback(callable) (required)
Function that fills the widget with the desired content. The function should echo its output.
$control_callback(callable)
Function that saves widget data: function that handle the submission of widget form (widget options), and also display the widget HTML form.
Default: null
$callback_args(array)
Data that will be passed to the $callback function. So $callback function receive $post object and the data specified in this parameter.
Default: null

Examples

0

#1 Add a widget to the dashboard

// Register a widget on action
add_action( 'wp_dashboard_setup', 'add_dashboard_widgets' );

// A callback for registering a widget
function add_dashboard_widgets() {
	wp_add_dashboard_widget( 'my_dashboard_widget', 'Metabox for the dashbord', 'my_dashboard_widget_function' );
}

// Widget's content
function my_dashboard_widget_function( $post, $callback_args ) {
	echo 'Hello World! This is my first widget!';
}
0

#2 Add a widget to the multisite dashboard

// Add a widget usining an anoynymous function
add_action( 'wp_network_dashboard_setup', function() {
	wp_add_dashboard_widget( 'my_dashboard_widget', 'A meta box in the dashboard of the multisite', 'my_dashboard_widget_function' );
} );

function my_dashboard_widget_function( $post, $callback_args ) {
	echo 'Hello! This is a widget on the dashboard of the multisite network!';
}
0

#3 Changing the widget location

This function does not allow you to specify the location of the widget and, by default, the position of the widget will be at the end of the first (left) column. Because of this function works based on add_meta_box() function, we can use it instead, it allows to specify the location of the widget (in which column it should be shown). Technically, all widgets are added to the global $wp_meta_boxes array, changing the location of the widgets in it, you can change their real location. However, we need to remember that the location of the widgets saves to WP user options when we drag them, and this, in turn, can affect the final location of the $wp_meta_boxes array elements.

Let's place the widget in the right column by specifying the fourth $post_type parameter for the add_meta_box() function.

add_meta_box( 'id', 'Dashboard Widget Title', 'dash_widget', 'dashboard', 'side', 'high' );

For multisite network the fourth parameter should be dashboard-network:

add_meta_box( 'id', 'Network Dashboard Widget Title', 'widget_output_func', 'dashboard-network', 'normal', 'high' );
0

#4 Using $control_callback parameter

With $control_callback parameter we can add a configuration section to the widget. The code below will register this widget:

Which has this configuration:

add_action( 'wp_dashboard_setup', 'prefix_add_dashboard_widget' );

function prefix_add_dashboard_widget(){

	wp_add_dashboard_widget(
		'my_dashboard_widget',
		'Featured Dashboard Page',
		'prefix_dashboard_widget',
		'prefix_dashboard_widget_handle'
	);
}

function prefix_dashboard_widget(){

	// get saved data
	if( ! $widget_options = get_option( 'my_dashboard_widget_options' ) )
		$widget_options = array( );

	// default output
	$output = sprintf(
		'<h2 style="text-align:right">%s</h2>',
		__( 'Please, configure the widget ☝' )
	);

	// check if saved data contains content
	$saved_feature_post = isset( $widget_options['feature_post'] )
		? $widget_options['feature_post'] : false;

	// custom content saved by control callback, modify output
	if( $saved_feature_post ) {
		$post = get_post( $saved_feature_post );
		if( $post ) {
			$content = do_shortcode( html_entity_decode( $post->post_content ) );
			$output = "<h2>{$post->post_title}</h2><p>{$content}</p>";
		}
	}

	echo '
	<div class="feature_post_class_wrap">
		<label style="background:#ccc;">'. $output .'</label>
	</div>
	';
}

function prefix_dashboard_widget_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['feature_post'] = absint( $_POST['my_dashboard_widget_options']['feature_post'] );
		# save update
		update_option( 'my_dashboard_widget_options', $widget_options );
	}

	// set defaults
	if( ! isset( $widget_options['feature_post'] ) )
		$widget_options['feature_post'] = '';

	$dropdown = wp_dropdown_pages( [
		'post_type'        => 'page',
		'selected'         => $widget_options['feature_post'],
		'name'             => 'my_dashboard_widget_options[feature_post]',
		'id'               => 'feature_post',
		'show_option_none' => '- Select -',
		'echo'             => 0,
	] );

	echo '
	<p><strong>Available Pages</strong></p>
	<div class="feature_post_class_wrap">
	<label>Title</label>'. $dropdown .'</div>';
}
0

#5 A widget for notes in the dashboard

The example below shows how to create a dashboard widget for notes. It saves the note content to WP options using AJAX.

This widget can be useful when you need to quickly write something to remember when you're in the dashboard.

<?php
/**
 * Plugin Name: Ajax WordPress Lessons
 * Description: Displays a widget with notes on the dashboard.
 * Plugin URI: https://github.com/campusboy87/lessons-ajax-wordpress
 * Author: Educational YouTube channel "WP-PLUS"
 * Author URI: https://www.youtube.com/c/wpplus
 */

// Registers "My notes" widget
add_action( 'wp_dashboard_setup', 'my_notes_dashboard_widget' );
function my_notes_dashboard_widget() {
	// Registers a widget only for administrators
	if ( current_user_can( 'activate_plugins' ) ) {
		wp_add_dashboard_widget( 'my_notes', 'My notes', 'my_notes_form' );
	}
}

// Displays the content of the widget
function my_notes_form() {
	?>

	<form>
		<textarea><?php echo esc_textarea( get_option( 'my_notes_content' ) ); ?></textarea>
		<button type="reset" class="clear button button-secondary">Clear</button>
		<?php submit_button( null, 'primary', null, false ); ?>
	</form>

	<?php
}

// Saves the note content using AJAX
add_action( 'wp_ajax_my_notes', 'my_notes_ajax_save' );
function my_notes_ajax_save() {
	check_ajax_referer( 'my_notes_nonce', 'security' );

	if ( ! isset( $_POST['my_notes_content'] ) || ! current_user_can( 'activate_plugins' ) ) {
		return;
	}

	// Get and sanitize the data
	$notes_content = sanitize_textarea_field( wp_unslash( $_POST['my_notes_content'] ) );

	// Saves the data to the option of the widget
	$status = update_option( 'my_notes_content', $notes_content, false );

	if ( $status ) {
		wp_send_json_success( [
			'message' => 'The note is saved',
		] );
	} else {
		wp_send_json_error( [
			'message' => 'The note is not saved',
		] );
	}

}

// Custom styles, and JS for saving the note content using AJAX.
add_action( 'admin_print_scripts', 'my_notes_scripts', 999 );
function my_notes_scripts(){

	// Exit from the function if the current page is not the main page of the dashboard (where the widgets are located)
	if ( 'dashboard' != get_current_screen()->base ) {
		return;
	}
	?>
	<style>
		#my_notes textarea {
			width: 100%;
			min-height: 100px;
			margin-bottom: 5px;
		}
	</style>

	<script>
		jQuery(document).ready(function ($) {
			var $boxNotes = $('#my_notes');
			var boxTitle = $('h2 span', $boxNotes).text();

			// Clean the note content
			$('.clear', $boxNotes).click(function () {
				$('textarea', $boxNotes).text('');
				$('h2 span', $boxNotes)
					.text('The field is cleared. Don`t forget to save the result!')
					.css('color', 'orangered');
			});

			// Send a form using AJAX
			$('form', $boxNotes).submit(function (e) {
				e.preventDefault();

				// Animation
				$boxNotes.animate({opacity: 0.5}, 300);

				// AJAX
				var request = $.post(
					ajaxurl,
					{
						action: 'my_notes',
						my_notes_content: $('textarea', $boxNotes).val(),
						security: '<?php echo wp_create_nonce( "my_notes_nonce" ); ?>'
					}
				);

				// Success
				request.done(function (response) {
					var $title = $('h2 span', $boxNotes).text(response.data.message);
					if (response.success) {
						$title.css('color', 'green');
					} else {
						$title.css('color', 'orangered');
					}
				});

				// Fail
				request.fail(function () {
					$('h2 span', $boxNotes)
						.text('ERROR: unknown error!')
						.css('color', 'red');
				});

				// Else
				request.always(function () {
					$boxNotes.animate(
						{opacity: 1},
						300,
						'',
						function () {
							setTimeout(function () {
								$('h2 span', $boxNotes)
									.text(boxTitle)
									.attr('style', '');
							}, 2000);
						});
				});

			});
		});
	</script>
	<?php
}

And we will get the following widget:

Notes

  • Global. callable[]. $wp_dashboard_control_callbacks

Changelog

Since 2.7.0 Introduced.
Since 5.6.0 The $context and $priority parameters were added.

wp_add_dashboard_widget() code WP 6.8

function wp_add_dashboard_widget( $widget_id, $widget_name, $callback, $control_callback = null, $callback_args = null, $context = 'normal', $priority = 'core' ) {
	global $wp_dashboard_control_callbacks;

	$screen = get_current_screen();

	$private_callback_args = array( '__widget_basename' => $widget_name );

	if ( is_null( $callback_args ) ) {
		$callback_args = $private_callback_args;
	} elseif ( is_array( $callback_args ) ) {
		$callback_args = array_merge( $callback_args, $private_callback_args );
	}

	if ( $control_callback && is_callable( $control_callback ) && current_user_can( 'edit_dashboard' ) ) {
		$wp_dashboard_control_callbacks[ $widget_id ] = $control_callback;

		if ( isset( $_GET['edit'] ) && $widget_id === $_GET['edit'] ) {
			list($url)    = explode( '#', add_query_arg( 'edit', false ), 2 );
			$widget_name .= ' <span class="postbox-title-action"><a href="' . esc_url( $url ) . '">' . __( 'Cancel' ) . '</a></span>';
			$callback     = '_wp_dashboard_control_callback';
		} else {
			list($url)    = explode( '#', add_query_arg( 'edit', $widget_id ), 2 );
			$widget_name .= ' <span class="postbox-title-action"><a href="' . esc_url( "$url#$widget_id" ) . '" class="edit-box open-box">' . __( 'Configure' ) . '</a></span>';
		}
	}

	$side_widgets = array( 'dashboard_quick_press', 'dashboard_primary' );

	if ( in_array( $widget_id, $side_widgets, true ) ) {
		$context = 'side';
	}

	$high_priority_widgets = array( 'dashboard_browser_nag', 'dashboard_php_nag' );

	if ( in_array( $widget_id, $high_priority_widgets, true ) ) {
		$priority = 'high';
	}

	if ( empty( $context ) ) {
		$context = 'normal';
	}

	if ( empty( $priority ) ) {
		$priority = 'core';
	}

	add_meta_box( $widget_id, $widget_name, $callback, $screen, $context, $priority, $callback_args );
}
1 comment
    Log In