Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Create small dashboard widget

i built an small/simple example and i hope it will help you.

Admin dashboard widget with an save button

Admin dashboard widget with an save button

First, we register a function which tells wordpress that we want to create an admin dashboard widget

/**
 * Registration of the Admin dashboard widget
 */
function ch_add_dashboard_widgets() {

    wp_add_dashboard_widget(
        'user_email_admin_dashboard_widget',      // Widget slug
        __('Extra profile information', 'ch_user_widget'),         // Title
        'ch_user_email_admin_dashboard_widget' // Display function
    );  
}

// hook to register the Admin dashboard widget
add_action( 'wp_dashboard_setup', 'ch_add_dashboard_widgets' );

Then we create the function that renders your widget

/**
 * Output the html content of the dashboard widget
 */
function ch_user_email_admin_dashboard_widget() {

  // detect the current user to get his phone number
  $user = wp_get_current_user();
  ?>


  <form id="ch_form" action="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>" method="post" >

    <!-- controlls on which function the post will send -->
    <input type="hidden" name="cp_action" id="cp_action" value="ch_user_data">

    <?php wp_nonce_field( 'ch_nonce', 'ch_nonce_field' ); ?>

    <p>Please add your phone number</p>

    <p>
        <label for="phone">Phone Number</label>
        <input type="text" name="phone" id="cp_phone_number" value="<?php echo esc_attr( get_the_author_meta( 'phone', $user->ID ) ); ?>" class="regular-text" />
    </p>
    <p>

      <input name="save-data" id="save-data" class="button button-primary" value="Save" type="submit">  
      <br class="clear">
    </p>

</form>

<?php
}

Ok the next part is the saving. There are two ways to save your widget data.

The first one is to send the data via a normal “form-post-request”. That the way how typical forms on websites works. Which means you have an form, you put your date in, hit the submit button and the data will send to the server. The server does someting with that data and than the user will redirect to onther page for instance an “Thank you”-page.

The second way is almost the same as the first but with one exception the “form-post-request” will send via AJAX (short for “Asynchronous JavaScript And XML“). The advantage of this way is, we stay on the same page (expressed in a very simple way).

To you use the second way we have to tell wordpress two thinks. First which function should be called by the ajax request and where your javascript file lies.

/**
 * Saves the data from the admin widget
 */
function ch_save_user_data() {

    $msg = '';
    if(array_key_exists('nonce', $_POST) AND  wp_verify_nonce( $_POST['nonce'], 'ch_nonce' ) ) 
    {   
       // detect the current user to get his phone number
       $user = wp_get_current_user();

       // change the phone number
       update_usermeta( $user->id, 'phone', $_POST['phone_number'] );

       // success message
       $msg = 'Phone number was saved';
    }
    else
    {   
       // error message
       $msg = 'Phone number was not saved';
    }

    wp_send_json( $msg );
}

/**
 * ajax hook for registered users
 */
 add_action( 'wp_ajax_ch_user_data', 'ch_save_user_data' );



/**
 * Add javascript file
 */
function ch_add_script($hook){

   // add JS-File only on the dashboard page
   if ('index.php' !== $hook) {
       return;
   }

   wp_enqueue_script( 'ch_widget_script', plugin_dir_url(__FILE__) ."/js/widget-script.js", array(), NULL, true );
}

/**
 * hook to add js
 */
add_action( 'admin_enqueue_scripts', 'ch_add_script' );

ok the last point this the content of the javascript file.

jQuery("#ch_form").submit(function(event) {

   /* stop form from submitting normally */
   event.preventDefault();

  /* get the action attribute from the form element */
  var url = jQuery( this ).attr( 'action' );

  /* Send the data using post */
  jQuery.ajax({
    type: 'POST',
    url: url,
    data: {
        action: jQuery('#cp_action').val(),
        phone_number: jQuery('#cp_phone_number').val(), 
        nonce: jQuery('#ch_nonce_field').val()
    },
    success: function (data, textStatus, XMLHttpRequest) {
        alert(data);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown);
    }
  });

});

Ok and to the end some usefull links:

“AJAX in Plugins” on wordpress.org

What is Ajax? Plugin Handbook on wordpress.org

Dashboard Widgets API on wordpress.org

Handling POST Requests the WordPress Way on sitepoint.com

EDIT:

I put the whole code into an plugin and published it on github.

Link: https://github.com/user141080/admindashboardwidget

Related Posts:

  1. Add ‘Right Now’ widget to custom dashboard
  2. Organizing the position of widgetized areas in the backend
  3. Make Widget appear on Dashboard
  4. Update widget form after drag-and-drop (WP save bug)
  5. How do register_sidebar() and get_sidebar() work together?
  6. Widgets vs. Theme Mods
  7. Widgets not working in Customizr but working in Appearance
  8. Get the sidebar ID in which the current widget was dropped
  9. How Can A Widget With Only One Instance Be Defined?
  10. How to exclude certain widget from showing up on home/front page? [duplicate]
  11. Customise search form in the Widget
  12. Created Widget Not Showing up on Admin Panel
  13. Custom Dashboard Home Screen Options
  14. Schedule cron event from widget
  15. How to Register and Display Widget for Custom taxonomy
  16. register_sidebar ‘after_widget’ on custom-built widgets not implementing, caused nested widgets
  17. Add new section to “Right Now” widget
  18. Count widgets of a certain type
  19. Widget Javascript code (ajax)
  20. Custom widget select options needs to stay selected after save
  21. Custom Widget form function common elements
  22. Updating Widget options in custom install.php
  23. Replace “WordPress” word in title of Dashboard
  24. Modify a theme to insert custom widgets?
  25. How did I enable atom feeds in a fresh WP3 install?
  26. How to update preview when custom setting changed in my custom widget
  27. Child Theme – how to add new widget on a specific place?
  28. Warning: Creating default object… when altering Customize panels
  29. Adding custom field in all widgets, but at the top of the form, in admin area
  30. How do I change the markup only of a built-in widget?
  31. Is it possible to make widget return only data (eg, array)?
  32. Allow a Widget to be used one time only?
  33. Search widget will search everything in the site, how to limit to only search gallery name
  34. Disable widgets in customizer for sidebar
  35. Unable to edit the “customize” section and the “widget” section is populating unknown code
  36. Choose sidebars column in widgets.php page [closed]
  37. Can’t receive $args[ ] to my custom widget
  38. how to convert Html block to dynamic widget?
  39. I’d like to move the Widgets Panel to the bottom of the list in Customizer
  40. Custom Log In Screen – Disable password recovery [duplicate]
  41. Can I add/replace the WordPress image in the Dashboard
  42. Widgets won’t save
  43. Customizing the Widget content markup
  44. Widget title markup in register_sidebar
  45. Sticky menu for WP custom menubars
  46. How to append custom text to the output of ‘categories widget’?
  47. Customise the Category Widget
  48. What’s the right way to share data between widgets?
  49. User Custom Dashboard
  50. Customize Widget Navigation
  51. Add custom border across footer widget area
  52. Customize section does not show my widget areas
  53. Widget recent comment filter by post meta_value
  54. How to create custom backend admin menu in different languages?
  55. How could I change contact details in the footer?
  56. remove screenshot.png via dashboard
  57. how to edit or remove the dashboard footer message [duplicate]
  58. How to narrow the area between buttons on Helium theme sidebar? [closed]
  59. How to display custom admin pointers (tips/notifications) in Dashboard until dismissed?
  60. How to hide or remove a custom widget area when empty
  61. Execute function with jQuery if widget added or removed?
  62. Still desperate about multiple TinyMCEs in widgets – is there any good solution to this yet?
  63. Custom Admin Section
  64. How to define active widget with js in a customizer
  65. Show WP content on different PHP Sites
  66. Confused about customising widgets
  67. Special characters showing in fallback font
  68. customize footer widgets area
  69. Create dashboard setting which lets me set ID of category which is inserted into template
  70. How do I include the sidebar (with Widgets) in a custom theme?
  71. Import bootstrap 5 and bootstrap icons in wp-admin backend
  72. Hover Hide-Visible Additional CSS not working in WordPress website, but shows properly in Customize window
  73. Add a custom field for sorting the products in a specific category WOOCOMMERCE – Second try
  74. Multiple Inputs in a Customizer Control
  75. Embedding a SOAP Client into a WordPress Plugin?
  76. Why do I get the timeout warning?
  77. Verify nonce in REST API?
  78. Add custom html to last sub-menu item
  79. Manipulating post meta in the customizer
  80. Rearrange elements outputted by comment_form()
  81. How to build custom WP admin with custom URLs
  82. Custom editor field displaying HTML in Visual editor
  83. generate unique number when registering a user
  84. Php custom query function assistance
  85. How can I manage my multiple wordpress websites from main website?
  86. How to set default values for options page
  87. How do I deque the default stylesheet?
  88. How to import custom data via XML, CSV, etc
  89. Why are Shortcodes Disabled in Widgets by Default?
  90. How to remove query string from static resource in WordPress?
  91. WordPress custom login page
  92. How do you modify the WordPress directory structure?
  93. Change WooCommerce product price based on category and GEO IP country
  94. How can I defer these JS files?
  95. Allow non-admins to access the Customize theme page
  96. Front-end delete account in WordPress
  97. Query post for ‘selected category’ in archive.php
  98. Add Custom API Call to WP-Login.php
  99. Unable to sanitize in customizer and escape in theme without removing ability for user to use “< br >” to insert a line break
  100. Fire on widgets_init only on dashboard
Categories customization Tags account, customization, dashboard, widgets
Calling a WordPress Custom JavaScript file
How to define custom links in WordPress

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress