How to Build Custom Dashboard Widgets

How to Build Custom Dashboard Widgets

Tutorial Details
  • Program: WordPress
  • Difficulty: Easy
  • Estimated completion time: 20 minutes

The WordPress Dashboard is a great place to see updates, or any kind of information related to your activity. In this tutorial, we’ll see how to dispose of default widgets and how to create your own custom widgets.

We are going to create a simple plugin to handle this so it can apply to any theme.


1. Create the Plugin

Create a new folder in the plugins directory (wp-content/plugins) and put a file named dashboard_widgets.php there.

<?php
/*
Plugin Name: Wptuts+ Dashboard Widgets
Plugin URI:
Description: Create custom dashboard widgets
Version: 0.1
Author: Guillaume Voisin
Author URI: http://wp.tutsplus.com/author/guillaumevoisin
License: GPL2
*/

Save it and it will already be available for activation in the plugins page.

We are now going to create the class that will hold our functions.

class Wptuts_Dashboard_Widgets {

	function __construct() {
		add_action( 'wp_dashboard_setup', array( $this, 'remove_dashboard_widgets' ) );
		add_action( 'wp_dashboard_setup', array( $this, 'add_dashboard_widgets' ) );
	}

	function remove_dashboard_widgets() {

	}

	function add_dashboard_widgets() {

	}

}

$wdw = new Wptuts_Dashboard_Widgets();

We will use the wp_dashboard_setup hook to bind two functions:

  • remove_dashboard_widgets will be used to remove the default widgets
  • add_dashboard_widgets will be used to add some of our own
Notice the way we bind the functions array( $this, 'remove_dashboard_widgets' ). Because it is a class, you have to tell WordPress the function belongs this class.

2. Define Our Widgets

Let’s create another file named custom_widgets.php. It will contain our widgets definitions (both to remove default and add new ones).

First, let’s add some widgets to be removed. It is basically an array which contains IDs of widgets to remove and information on where to delete them (page and context).

For this purpose, we will use the function remove_meta_box() as dashboard’s widgets are built as metaboxes. The function has three arguments:

  • ID
  • Page – Where can we find this widget ( dashboard / post / attachment / … )
  • Context – In which area is the widget located ( normal / advanced / side )

Now, let’s set those parameters:

$remove_defaults_widgets = array(
	'dashboard_incoming_links' => array(
		'page'    => 'dashboard',
		'context' => 'normal'
	),
	'dashboard_right_now' => array(
		'page'    => 'dashboard',
		'context' => 'normal'
	),
	'dashboard_recent_drafts' => array(
		'page'    => 'dashboard',
		'context' => 'side'
	),
	'dashboard_quick_press' => array(
		'page'    => 'dashboard',
		'context' => 'side'
	),
	'dashboard_plugins' => array(
		'page'    => 'dashboard',
		'context' => 'normal'
	),
	'dashboard_primary' => array(
		'page'    => 'dashboard',
		'context' => 'side'
	),
	'dashboard_secondary' => array(
		'page'    => 'dashboard',
		'context' => 'side'
	),
	'dashboard_recent_comments' => array(
		'page'    => 'dashboard',
		'context' => 'normal'
	)
);

Then, we define the custom widgets we want to add. To add WordPress custom widgets, we will use the built-in function wp_add_dashboard_widget(). The function takes several arguments:

  1. ID
  2. Title – Title of our widget
  3. Callback – Function to handle the widget’s content

So let’s define our widget and set those parameters. For this tutorial, we’ll create a very simple dashboard widget that will display the current users’ last published posts.

$custom_dashboard_widgets = array(
	'my-dashboard-widget' => array(
		'title' => 'My Dashboard Widget',
		'callback' => 'dashboardWidgetContent'
	)
);

As the callback option required a valid function to handle the widget’s content, let’s add a function for this.

function dashboardWidgetContent() {
	$user = wp_get_current_user();
	echo "Hello <strong>" . $user->user_login . "</strong>, this is your custom widget. You can, for instance, list all the posts you've published:";

	$r = new WP_Query( apply_filters( 'widget_posts_args', array(
		'posts_per_page' => 10,
		'post_status' => 'publish',
		'author' => $user->ID
	) ) );

	if ( $r->have_posts() ) :
	?>

	<?php
	endif;
}

Now we’ve defined the widgets we want to remove from the dashboard as well as the ones we want to create, we can focus back to our class.


3. Do the Magic!

Now, all that’s left to do is to actually add and remove those widgets.

So get back to our class and let’s fill in the blanks left in Step 1.

First of all, let’s include our widgets definition so they’ll be available in our class. Add this line at the top of dashboard_widgets.php:

require_once( plugin_dir_path( __FILE__ ) . '/custom_widgets.php' );

Remove Widgets

function remove_dashboard_widgets() {
	global $remove_defaults_widgets;

	foreach ( $remove_defaults_widgets as $widget_id => $options ) {
		remove_meta_box( $widget_id, $options['page'], $options['context'] );
	}
}

To remove our widgets, we just loop through our $remove_defaults_widgets array and apply the remove_meta_box function with the parameters we set for each widget.

Be sure to “globalize” the $remove_defaults_widgets variable, otherwise you won’t be able to use it.

Add Custom Widgets

function add_dashboard_widgets() {
	global $custom_dashboard_widgets;

	foreach ( $custom_dashboard_widgets as $widget_id => $options ) {
		wp_add_dashboard_widget(
			$widget_id,
			$options['title'],
			$options['callback']
		);
	}
}

Exact same process here, except we apply the wp_add_dashboard_widget function.

Now save and go to your dashboard, you should come to something like below:

Dashboard with custom widgets

Conclusion

Now, you can add whatever widget you want to your WordPress’ dashboard, simply by adding options and callbacks to the custom_widgets.php file.

It’s always a good idea to customize the dashboard, especially when it is for a client. You can list their last articles, comments, reminders, etc. So it becomes a convenient place to start from.

Let us know what you think in the comments below, especially if you have more suggestions on customising the WordPress Dashboard for clients.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.facebook.com/bob.murphy.399 Bob Murphy

    Great article. Can you please explain how in

    foreach ( $remove_defaults_widgets as $wigdet_id => $options ) {
    remove_meta_box( $wigdet_id, $options['page'], $options['context'] );

    that $wigdet_id becomes an actual ID ( from the previous line it looks like a key from the `
    $wigdet_id => $options` line. I suppose it’s to do with how php works on some level.

    I also wanted to ask about ( or point out ) the two different spellings widget and wigdet in the code. Is this intentional?

    • Guillaume
      Author

      It is just a typo, needs to be “widget”.

      • http://wp.tutsplus.com/ Japh

        Hey guys, just letting you know I’ve updated the post to remove the typo.

  • Pingback: WordPress news: March 10 to March 16, 2013

  • http://www.wpguru.com.au/ Robin Thebs

    Great thnx … A good tutorials to set up for coming up Premium Series …

  • Guest

    $widget_id is the id of one specific widget that is in an array of widgets that should be removed hence why it is singular and $remove_defaults_widgets is plural. We also pass the options so that wordpress knows exactly where the metabox we want to move is located.

  • Pingback: Как создать настраиваемые виджеты для консоли WordPress | Wordpresso

  • http://twitter.com/tyndev Michael Tyndev

    Is the Widget API different from creating custom dashboard widgets? I started the tutsplus course on widgets and so far they seem completely separate. There’s no course forum there yet and the author overlooked putting in a “what are widgets” video.

    • Guillaume
      Author

      I omitted to talk about widgets on purpose, because indeed it is a different API. Building widgets for dashboard is about creating metaboxes whereas buildings sidebar widgets is about classes with specific methods (widget, form, …).

  • Pingback: WordPress News Roundup – Mar 2013 – No3

  • http://twitter.com/Frenkix Goran Jakovljevic

    I am not php expert unfortunatly, so just quick question, why did we use constructor, could we do this without it, what are benefits ? Learning OOP and trying to figure out things :)

  • Pingback: WordPress news: March 10 to March 16, 2013 | Uber Patrol - The Definitive Cool Guide