Add a Custom Dashboard Widget in WordPress

You can add your own widget to the admin dashboard, for example to show a message, a link list or a site statistic. Use wp_add_dashboard_widget() on the wp_dashboard_setup hook.

<?php
add_action( 'wp_dashboard_setup', function () {
	wp_add_dashboard_widget(
		'tc_site_stats',          // widget ID
		'Site Statistics',        // title
		'tc_site_stats_content'   // function which prints the content
	);
} );

function tc_site_stats_content() {
	$counts = wp_count_posts();
	printf(
		'<p>Published posts: <strong>%d</strong></p><p>Drafts: <strong>%d</strong></p>',
		(int) $counts->publish,
		(int) $counts->draft
	);
}

Test it

We log in as the admin (like a browser) and read the dashboard page:

Terminal output

$ curl -s -b cookies.txt http://example.com/wp-admin/index.php | grep -o -E 'id="tc_site_stats"|Site Statistics|<p>Published posts: <strong>[0-9]*</strong></p><p>Drafts: <strong>[0-9]*</strong></p>' | sort -u
<p>Published posts: <strong>1</strong></p><p>Drafts: <strong>1</strong></p>
Site Statistics
id="tc_site_stats"

The widget is on the dashboard with the numbers. Show it only to some users by checking current_user_can( 'manage_options' ) before you call wp_add_dashboard_widget().


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.