Add a dashboard widget in WordPress admin panel

With wordpress 2.7 came the dashboard widgets that you can easily customize, add or remove. Now lets say you have a great plugin that gets some kind of stats. Wouldn’t it be nice to display them on the dashboard so you can view them in one swift eye move rather than going in you plugin pages?

Alright you guessed, I am a lazy one. The less I click the better I feel. So here is how to add a widget on your blog dashboard.

dashboard-intro

Create the widget

When wp loads up the dashboard it triggers the wp_dashboard_setup actions. We can add our own action using the add_action function. You pass it two parameters: the event to listen to, here wp_dashboard_setup and the function to callback.

/**
 * use hook, to integrate new widget
 */
add_action('wp_dashboard_setup', 'countPost_wp_dashboard_setup');

/**
 * add Dashboard Widget via function wp_add_dashboard_widget()
 */
function countPost_wp_dashboard_setup() {
	wp_add_dashboard_widget( 'my_wp_dashboard_test', __( 'Content Blog Counter' ), 'countPost_wp_dashboard' );
}

The function called by the action has only one line of code in it. This line is what creates the widget itself. And of course it automatically comes with drag-and-drop and styling.

wp_add_dashboard_widget accept three parameters: id of the widget, title and callback function to execute when the widget is created. Now we just need to populate this widget with some data:

/**
 * Content of Dashboard-Widget
 */
function countPost_wp_dashboard() {
	
	$current_year = date("Y");
	$current_month = date("m");
	
	$query = new WP_Query();
	$query->query(array('year'=> $current_year, 'monthnum'=>$current_month, 'showposts'=>'-1'));
	
	echo "<p>Post published this month: ".$query->post_count."</p>";

}

Stick all that in your functions.php or in a plugin and it should work straight away.

In this example I echo the number of posts written in the current month. I know, it is not the most useful data…but you can certainly come with something better.

Related Items and Services:
new Photovoltaic Panels
Voile Panels sold here

2 responses to “Add a dashboard widget in WordPress admin panel”

  1. AvtoMn

    Good article, but i don’t use wordpress :(

Leave a Reply

  1. Add a dashboard widget in WordPress admin panel

    [...] Visit Source. [...]

Theme Forest ad
Wordpress Themes Collection ad
Woothemes

Poll

How do you start your WordPress plugins development projects?

View Results

Loading ... Loading ...