× {{alert.msg}} Never ask again
Receive New Tutorials
GET IT FREE

Adding Custom Widgets to Your WordPress Dashboard: A Detailed Guide

– {{showDate(postTime)}}

As a WordPress user, you might have definitely wished for a dashboard that is much more organized and easy to use. Fortunately, there is a method that can be followed for adding completely customized widgets to your WordPress website’s admin dashboard. This is what I’ve covered in this tutorial.

Anatomy of a basic dashboard widget

You need to use the wp_add_dashboard_widget() function for registering a widget with WordPress. After this, you’ll be required to create a separate function which would handle the display of content within the added widget. The template code used for creating a dashboard widget is shown below:

add_action( 'wp_dashboard_setup', 'register_first_custom_dashboard_widget' );
function register_first_custom_dashboard_widget() {
    wp_add_dashboard_widget(
        'my_first_custom_dashboard_widget',
        'My Custom Dashboard Widget',
        'my_first_custom_dashboard_widget_display'
    );

}

function my_first_custom_dashboard_widget_display() {
    echo 'Hello, I am Mr. Widget';
}

If you read the above code carefully, you’ll find that the function called wp_dashboard_setup will include content which will be a simple call to wp_add_dashboard including three parameters viz: Widget slug, Widget title and Display function.

Displaying information or functionality

towards the top of WordPress admin dashboard

Well, WordPress doesn’t have a good API for showcasing functionality towards the top of dashboard. Therefore, for making this possible, all you need to do is simply add the below code snippet into your registration function:

function register_first_custom_dashboard_widget() {
     global $wp_meta_boxes;

    wp_add_dashboard_widget(
        'my_first_custom_dashboard_widget',
        'Publication Schedule',
        'my_first_custom_dashboard_widget_display'
    );

     $dashboard = $wp_meta_boxes['dashboard']['normal']['core'];

    $my_widget = array( 'my_first_custom_dashboard_widget' => $dashboard['my_first_custom_dashboard_widget'] );
     unset( $dashboard['my_first_custom_dashboard_widget'] );

     $sorted_dashboard = array_merge( $my_widget, $dashboard );
     $wp_meta_boxes['dashboard']['normal']['core'] = $sorted_dashboard;
}
add_action( 'wp_dashboard_setup', 'register_first_custom_dashboard_widget' );

function my_first_custom_dashboard_widget_display() {
    ?>

<p>
Don't forget that there are three slots for publication each day. <strong>8am, 1pm and 6pm</strong> EDT. Posts must be finalized 12 hours before their publication time. This includes final checks and proofreading.
</p>
 
<p>
For particularly time-sensitive posts please contact the editor in chief to make sure the required time does not conflict with any ongoing projects.
</p>
 
<?php
} 

Here’s an explanation of the above code:

  • As the first step, I’ve globalized the $wp_meta_boxes variable which includes all the information related to the registered widgets. Here, I’ve segregated the dashboard widgets using the $dashboard variable.
  • As the second step, I’ve fetched my registered widget from the array of widgets stored in the $new_widget variable.
  • As the third step, I’ve merged the contents of $new_widget and $dashboard. Here, the array_merge() function will append the second array to the first one, thereby making the widget appear as the first one within the #sorted_dashboard array.
  • As the fourth and last step, I’ve replaced the original WP dashboard with the new one.

Adding functionality

into the new custom widgets added to the WordPress admin dashboard

One of the most promising ways of enhancing the dashboard widgets is creating remarkable style or applying some simple JavaScript functionality. For instance, let us create a widget which displays the total number of comments which have been received by our website each week for the past seven weeks.

The HTML structure of this widget will be as shown below:

<div class="commentbars">
    <div class="commentbar"></div>
    <div class="commentbar"></div>

</div>
<div class="commentlabels">
    <div class="commentlabel">comment count listing here</div>
</div>
<div class='comment-stat-caption'>Comments in the past 7 weeks</div>

Now, the above widget will be styled using the CSS file and inline CSS which would handle the widget’s height and width.

Styling the comment bars

Both, the bars as well as the height of the entire container .comment-stat-bars has been fixed to 130px. Therefore, seemingly different heights for the two can be easily achieved by adding a certain top border height. Doing this will ensure that the comment bars initiate from the bottom. Also, we can hide the unwanted bits by setting overflow:hidden on the container.

The CSS stylesheet is being added in the traditional style(i.e. Enqueueing) as shown below:

add_action( 'admin_enqueue_scripts', 'dashboard_widget_css' );
function dashboard_widget_css( $hook ) {
    if( 'index.php' != $hook ) {
        return;
    }

    wp_enqueue_style( 'dashboard-widget-css', plugins_url( '', __FILE__ ) . '/dashboard_widgets.css' );
}

In the above code, the value of the $hook variable is being checked for ensuring that the style is just used on the admin dashboard page.

Here is the complete CSS for the content of stylesheet. All the remaining styles are being added inline as shown below:

.commentbars {
    overflow:hidden
}
 
.commentbar {
    margin:0 1%;
    background-color: #2ea2cc;
    border-top-color: #fff;
    border-top-style: solid;
    float:left;
}
 
.commentlabels {
    overflow:hidden;
}
 
.commentlabel {
    float:left;
    margin:0 1%;
    padding:5px 0;
    text-align:center;
}
 
.comment-caption {
    text-align:center;
    margin:11px 0;
    font-style:italic
}

Calculating the height of bars

Let’s work with an array like this:

$comment_counts=array(19, 28, 39, 32, 16);

The above array represents comments that have been received since last 7 weeks. When it comes to setting the width of bars, on using 100% as the total width, the percentage width of a single bar will be calculated like this:

// ( 100 / number of bars ) - 2

$data_points = count( $comment_counts );

$bar_width = 100 / $data_points - 2

Talking about the height of bars, the one with the highest value will be set to fill out the entire height of the container. The code associated with the same is shown below:

$highest_value = max( $comment_counts );

foreach( $comment_counts as $count ) :

    $count_percentage = $count/$highest_value;

    $bar_height = $total_height * $count_percentage;

    $border_width = $total_height - $bar_height;

}

Displaying the comments in the form of a static graph

The code associated with the same is shown below:

function dashboard_widget_css( $hook ) {
    if( 'index.php' != $hook ) {
        return;
    }

    wp_enqueue_style( 'dashboard-widget-css', plugins_url( '', __FILE__ ) . '/dashboard_widgets.css' );
}

add_action( 'admin_enqueue_scripts', 'dashboard_widget_css' );


function register_commentstat_dashboard_widget() {
    wp_add_dashboard_widget(
        'comment_stats_widget',
        'Comment Stats',
        'commentstats_dashboard_widget_display'
    );
}
add_action( 'wp_dashboard_setup', 'register_commentstat_dashboard_widget' );

function commentstats_dashboard_widget_display() {

    $comment_counts = array( 20, 29, 39, 33, 17 );
    $highest_value = max( $comment_counts );
    $data_points = count( $comment_counts );
    $bar_width = 100 / $data_points - 2;
    $total_height = 120;
    ?>;
 
    <div class="commentbars" style="height:<?php echo $total_height ?>px;">
        <?php
            foreach( $comment_counts as $count ) :
                $count_percentage = $count/$highest_value;
                $bar_height = $total_height * $count_percentage;
                $border_width = $total_height - $bar_height;
        ?>
        <div class="commentbar" style="height:<?php echo $total_height ?>px; border-top-width:<?php echo $border_width ?>px; width: <?php echo $bar_width ?>%;"></div>
        <?php endforeach ?>
    </div>
 
    <div class='commentlabels'>
        <?php foreach( $comment_counts as $count ) : ?>
        <div class='commentlabel' style='width: <?php echo $bar_width ?>%;'><?php echo $count ?></div>
    <?php endforeach ?>
    </div>
 
    <div class='comment-caption'>Comments in the past 7 weeks</div>
    <?php
}

Grabbing comment counts dynamically

In order to fetch the comment counts dynamically, all you need to do is simply replace your array with the following:

for( $i=1; $i <= 7; $i++ ) {

    $this_week = 7 * $i;

    $last_week = 7 * ( $i - 1);

    $comment_counts[] =

    $wpdb->get_var( "SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_date > '" . date('Y-m-d H:i:s', strtotime('-' . $this_week . ' days')) . "' AND comment_date < '" . date('Y-m-d H:i:s', strtotime('-' . $last_week . ' days')) . "'" ) ;

In the above code, I’m pulling the count of comments from the website’s database seven times. That means, in every single loop iteration, I’m going back a single week.

We’re done!

Final Thoughts

Customized dashboard widgets can add a whole lot of convenience in managing vital areas within the WordPress website. Hope the above post would’ve allowed you to learn a lot adding bespoke widgets to your plain, a bit messy WordPress dashboard.


Author Bio:

Samuel Dawson is a professional in Designs2HTML, A leading firm in the field of psd to html5 conversion. Samuel is also a serial blogger and loves to share various things on the web with others.




Questions about this tutorial?  Get Live 1:1 help from WordPress experts!
Stefan Georg
Stefan Georg
5.0
Senior Full Stack Software Developer
I've been coding since age of 15, starting with perl, moving to php, and finally to python. I've been a freelancer working in the US, New Zealand,...
Hire this Expert
Don Oktrova
Don Oktrova
5.0
Senior Software Developer
Self taught developer who have been developing for more than 15 years.
Hire this Expert
comments powered by Disqus