QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Add and Remove Widgets in WordPress Dashboard

Add and Remove Widgets in WordPress Dashboard

wordpress-dashboard-widgets-api

This post is a part 10 of Creating a WordPress Admin Theme post series.

In this article we will look at WordPress dashboard widgets API using which you can add and remove widgets into wordpress admin dashboard.


What is WordPress Admin Dashboard?

Screen Shot 2014-08-22 at 7.33.37 pm

WordPress admin dashboard is the first page that is shown when you login into the wordpress admin panel. This page has various default widgets. We can change the widgets locations by just dragging them to different positions. We can hide/unhide them using the arrow button on the right side of widget title and we can also enable/disable them using the screen options on top.
Screen Shot 2014-08-22 at 7.36.48 pm
Widgets can contain almost anything. They can used to create new information or display information.

WordPress dashboard widgets API allows you to create your own widgets for the dashboard.

WordPress Dashboard widgets are Meta Boxes

Believe me or not wordpress dashboard widgets are actually meta boxes on the dashboard page. When we add new meta boxes to posts/pages we call them custom meta boxes similarly when we add meta boxes to dashboard page we call them dashboard widgets.

WordPress Widgets API is just an wrapper for Meta Box API.

Creating a Dashboard Widget

New widgets can be created using wp_add_dashboard_widget function.

<?php
function display_custom_dashboard()
{
    //this function is used to create a widget.
    //first parameter -> unique id/slug for that widget
    //second parameter -> title of the widget
    //third parameter -> callback used to display content of the widget
    wp_add_dashboard_widget("qnimate", "QNimate News", "display_qnimate_news");
}

//callback to display the content in the widget
function display_qnimate_news()
{
    echo "Watch awesome courses at QScutter";
}

//fired before displaying widgets and after loading widgets API library.
add_action("wp_dashboard_setup", "display_custom_dashboard");

Screen Shot 2014-08-22 at 7.55.17 pm

Let’s see how to achieve the same using Meta Box APIs.

<?php
function display_qnimate_news()
{
    echo "Watch awesome courses at QScutter";
}


function my_custom_meta_box()
{
    add_meta_box("qnimate", "QNimate News", "display_qnimate_news", "dashboard");
}

//don't use add_meta_boxes action because its triggered only during posts/pages loading.
add_action("wp_dashboard_setup", "my_custom_meta_box");

Newly created widgets are kept at the end.

Removing Widgets

Dashboard widgets can be removed using the screen options. But sometimes you may need to remove them programatically.

Dashboard Widgets API doesn’t provide any function to remove default or manually created widgets. But Meta Box API provides us functions to remove meta boxes. As we need widgets are internally meta boxes so we can use the meta box API to remove the widgets.

remove_meta_box can be used to remove meta boxes.

<?php
function remove_dashboard_widgets()
{
    //first parameter -> slig/id of the widget
    //second parameter -> where the meta box is displayed, it can be page, post, dashboard etc.
    //third parameter -> position of the meta box. If you have used wp_add_dashboard_widget to create the widget or deleting default widget then provide the value "normal".
    remove_meta_box('dashboard_incoming_links', 'dashboard', "normal");
    remove_meta_box('dashboard_plugins', 'dashboard', 'normal');
    remove_meta_box('dashboard_primary', 'dashboard', 'normal');
    remove_meta_box('dashboard_secondary', 'dashboard', 'normal');
    remove_meta_box('dashboard_quick_press', 'dashboard', 'normal');
    remove_meta_box('dashboard_recent_drafts', 'dashboard', 'normal');
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
    remove_meta_box('dashboard_right_now', 'dashboard', 'normal');
    remove_meta_box('dashboard_activity', 'dashboard', 'normal');
}

add_action("wp_dashboard_setup", "remove_dashboard_widgets");

Screen Shot 2014-08-22 at 9.42.03 pm

Embedding Forms in Dashboard Widgets

While using custom meta boxes the forms were submitted to wp-admin/post.php URL. There we used to handle the “save_post” action(triggered during post request) and then used the add_post_meta(), delete_post_meta(), add_update_meta() and get_post_meta() to manipulate the data. We can say that Meta Box API doesn’t provide any standard way to handle form submissions.

But dashboard widgets API provide a easy way to handle handle form submissions. wp_add_dashboard_widget takes a fourth argument which is a callback for displaying forms and also handling the submission of forms.

Let’s see an example of displaying forms and handling submission of forms.

<?php
function display_custom_dashboard()
{
    wp_add_dashboard_widget("qnimate", "QNimate News", "display_qnimate_news", "display_qnimate_form");
}

function display_qnimate_news()
{
    echo "Watch awesome courses at QScutter";
}

//this callback is fired during display of form inside widget and also during form submission.
function display_qnimate_form()
{
    //if form is submitted
    if(isset($_POST["some_text"]))
    {
        update_option("qnimate_some_text", $_POST["some_text"]);
    }

        //form tag and submit button is automatically displayed by the dashboard API
    ?>
        <input type="text" name="some_text" id="some_text" placeholder="Enter some text" value="<?php echo get_option('qnimate_some_text'); ?>" />
    <?php
}

add_action("wp_dashboard_setup", "display_custom_dashboard");

By default the third callback is executed. To make the fourth callback to be executed you need to click the configure button on the right side of widget title.
Screen Shot 2014-08-22 at 10.33.25 pm

Here we were using the core functions of settings API to save and retrieve data.

Therefore depending on where we have embedded meta boxes we need to switch the saving and retrieving of data methods.

To handle file uploads via the form put this script in the fourth callback.

<?php
function display_qnimate_form()
{
    //if form is submitted
    if(isset($_POST["some_text"]))
    {
        update_option("qnimate_some_text", $_POST["some_text"]);
    }

    ?>
        <input type="text" name="some_text" id="some_text" placeholder="Enter some text" value="<?php echo get_option('qnimate_some_text'); ?>" />
        <script type="text/javascript">
            //we need to change the enctype of the form for file uploads.

            //pass the id/slug of widget in the getElementById argument
            var eleChild = document.getElementById("qnimate").childNodes;
            var inside = "";
            for( i = 0 , j = eleChild.length; i < j ; i++ )
            {
                if(eleChild[i].className == "inside")
                {
                    inside = eleChild[i];
                    break;
                }
            }

            eleChild = inside.childNodes;
            for( i = 0 , j = eleChild.length; i < j ; i++ )
            {
                if(eleChild[i].className == "dashboard-widget-control-form")
                {
                    //change the echtype to support file uploads. multipart/form-data doesn't encode the post data, encoding of binary file is not possible by post encoding standards.
                    eleChild[i].enctype = "multipart/form-data";
                    break;
                }
            }
        </script>
    <?php
}

Conclusion
I tried to cover all the important aspects of the dashboard widget API. If you have any questions then put it up in the comments. Thanks for reading. Please share it.

Aug 22, 2014Narayan Prusty
Customizing WordPress Admin ToolbarDisplay Google Plus Page Summary In Search Result For Your Brand
Comments: 1
  1. bharath
    5 years ago

    good evening sir..
    i thinking to add and remove my own dashboard widget from my plugin based my conditions
    how can i do in better way…??

    ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image8 years ago 1 Comment WordPress
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • What is WordPress Admin Dashboard?
  • WordPress Dashboard widgets are Meta Boxes
  • Creating a Dashboard Widget
  • Removing Widgets
  • Embedding Forms in Dashboard Widgets
Related Articles
  • Overview of WordPress Admin Menu API
  • WordPress Custom Meta Boxes Tutorial
  • Change Position of WordPress Dashboard Widget
  • Customizing WordPress Admin Toolbar
  • Customizing WordPress Admin Profile Page
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license