🎉 AgentWP is now in Public Beta Testing.
When you log in to your WordPress site, the first thing you see is your dashboard. But what if you could make it even better?
Imagine seeing exactly what matters most to you - your latest comments, site stats, to-do lists, etc., all in one place. Wouldn't that be great?
That's exactly what widgets are for. You can stay organized and updated. No need to switch between tabs or dig through the menus. Everything important is right there on your dashboard.
WordPress lets you create these custom widgets yourself. Now, if you're new to this, it might sound a bit intimidating. However, it's actually pretty doable, even if you're just starting out.
If this sounds interesting to you, then read on. In this guide, we'll show you how to use wp_add_dashboard_widget
, a built-in WordPress function, to create simple and complex widgets.
Understanding the wp_add_dashboard_widget
Function
At the core of creating dashboard widgets is the wp_add_dashboard_widget
function.Â
This function is important because:
- It allows you to extend WordPress functionality without modifying core files.
- It makes admin tasks easier by putting important data or controls right on the dashboard.
- It allows you to create more complex and interactive admin interfaces.
Let's break down how it works and how you can put it to use in your projects.
How Does the wp_add_dashboard_widget
Function Work?
With the wp_add_dashboard_widget
function, you can create your very own widget and display custom information or features right where administrators can easily see them.Â
Simply give your widget a unique ID (like naming your pet), a title for everyone to see, and tell it what to display. The function then hooks into the wp_dashboard_setup
action to ensure the widget fits perfectly into the admin interface. You can also add a control callback to handle widget settings if needed.Â
Basic Syntax of wp_add_dashboard_widget
The syntax of the wp_add_dashboard_widget
function includes several parameters that define the widget's properties and behavior.Â
Here's what it looks like:
wp_add_dashboard_widget( $widget_id, $widget_name, $callback, $control_callback, $callback_args );
Now, let’s explore each parameter:
$widget_id
: This is your widget's unique identifier. Think of it as your widget's name tag – it helps WordPress recognize and style your widget.$widget_name
: This is the title that users will see at the top of your widget. Make it clear and descriptive.$callback
: This is where you define what your widget will display. It's a function that generates the HTML content for your widget.$control_callback
(Optional): If you want to give users options to customize the widget, this is where you'd define that functionality.$callback_args
(Optional): Use this to pass additional information to your callback function if needed.
How It Works with the Dashboard
The wp_add_dashboard_widget
function works by hooking into the wp_dashboard_setup
action. This is essentially telling WordPress to register and display a new widget. When the dashboard loads, WordPress spots your widget. It then calls the callback function you've specified and generates the HTML content to render the widget’s content.Â
Let’s look at a practical example of how to use the wp_add_dashboard_widget
function:
// Hook into the 'wp_dashboard_setup' action to register our custom widget
add_action('wp_dashboard_setup', 'my_custom_dashboard_widget');
// Function to register the widget
function my_custom_dashboard_widget() {
  wp_add_dashboard_widget(
    'my_dashboard_widget',          // Widget slug
    'My Custom Dashboard Widget',      // Widget title
    'my_dashboard_widget_display'      // Display function
  );
}
// Function to display the widget content
function my_dashboard_widget_display() {
  echo '<p>Welcome to my custom dashboard widget!</p>';
}
Here, we’ve created a simple widget that displays a welcome message.
The my_custom_dashboard_widget
function registers a widget with the unique ID my_dashboard_widget
and the title My Custom Dashboard Widget
. The my_dashboard_widget_display
function defines the content of the widget, which in this case is a simple welcome message. The add_action
hook then integrates the widget into the dashboard during the wp_dashboard_setup
action.
Setting Up Your Environment
To get started with creating a custom WordPress dashboard widget, you'll need to have the following:
- The latest version of WordPress installed and running on your server
- Basic PHP and WordPress hooks knowledge
- A code editor like VS Code, Sublime Text, or Atom to write and modify your PHP files
- Access to your WordPress site and admin panel using any web browser
- WordPress admin privileges to add and manage dashboard widgets within WordPress
Optionally, if you want to speed things up, consider using our AI platform CodeWP. It's designed specifically for WordPress, so it understands everything from working on themes and plugins to customizing dashboard widgets.Â
Creating a Simple Dashboard Widget
Now, let’s create a simple dashboard widget called Admin To-Do List. This widget will allow WordPress users to manage their tasks directly from the dashboard.Â
Our widget features a simple interface with a text field for entering new to-do items and a Save To-Do List button. The entered tasks will appear as a bullet-point list above the input field so that users can easily track and edit their tasks.
Here's a breakdown of the steps we'll follow to create this custom dashboard widget:
Step 1: Write the Custom Code
For this example, we used CodeWP to quickly generate a functional code snippet as a starting point.
We began by providing CodeWP with the following prompt:
Create a simple to-do list for admin tasks. Include a text field where the user can enter tasks and a button to submit them. Display the entered tasks as a bullet list just above the text field. Each time a user enters a new task, it should be added to the list immediately.
Below is the AI-generated code:
function cwpai_register_todo_list_widget() {
  wp_add_dashboard_widget(
    'cwpai_todo_list_widget',
    'Admin To-Do List',
    'cwpai_display_todo_list_widget'
  );
}
add_action('wp_dashboard_setup', 'cwpai_register_todo_list_widget');
function cwpai_display_todo_list_widget() {
  $todo_list_items = array();
  if (isset($_POST['cwpai_todo_list_items'])) {
    $todo_list_items = get_option('cwpai_todo_list_items', array());
    $new_item = sanitize_text_field($_POST['cwpai_todo_list_items']);
    if (!empty($new_item)) {
      if (!is_array($todo_list_items)) {
        $todo_list_items = array();
      }
      $todo_list_items[] = $new_item;
      update_option('cwpai_todo_list_items', $todo_list_items);
    }
  } else {
    $todo_list_items = get_option('cwpai_todo_list_items', array());
  }
  echo '<ul>';
  foreach ((array) $todo_list_items as $item) {
    echo '<li>' . esc_html($item) . '</li>';
  }
  echo '</ul>';
  echo '<form method="post">';
  echo '<input type="text" name="cwpai_todo_list_items" style="width:100%;" placeholder="Enter your to-do item">';
  echo '<p><input type="submit" value="Save To-Do List" class="button-primary"></p>';
  echo '</form>';
}
function cwpai_todo_list_widget_css() {
  echo '<style>
    #cwpai_todo_list_widget ul {
      list-style-type: disc;
      padding-left: 20px;
    }
    #cwpai_todo_list_widget input[type="text"] {
      margin-top: 10px;
      padding: 8px;
      font-size: 14px;
      box-sizing: border-box;
    }
    #cwpai_todo_list_widget input.button-primary {
      margin-top: 10px;
    }
  </style>';
}
add_action('admin_head', 'cwpai_todo_list_widget_css');
Let’s break down each part of the code and explain its components.
Register the Widget Using wp_add_dashboard_widget
function cwpai_register_todo_list_widget() {
  wp_add_dashboard_widget(
    'cwpai_todo_list_widget',
    'Admin To-Do List',
    'cwpai_display_todo_list_widget'
  );
}
add_action('wp_dashboard_setup', 'cwpai_register_todo_list_widget');
In this code, we’re using the wp_add_dashboard_widget
function to register a new widget. Inside the function, we include a unique identifier cwpai_todo_list_widget
, a title Admin To-Do List
, and the function cwpai_tdisplay_todo_list_widget
to display the list.
Create the Callback Function to Display Content
function cwpai_display_todo_list_widget() {
  $todo_list_items = array();
  if (isset($_POST['cwpai_todo_list_items'])) {
    $todo_list_items = get_option('cwpai_todo_list_items', array());
    $new_item = sanitize_text_field($_POST['cwpai_todo_list_items']);
    if (!empty($new_item)) {
      if (!is_array($todo_list_items)) {
        $todo_list_items = array();
      }
      $todo_list_items[] = $new_item;
      update_option('cwpai_todo_list_items', $todo_list_items);
    }
  } else {
    $todo_list_items = get_option('cwpai_todo_list_items', array());
  }
  echo '<ul>';
  foreach ((array) $todo_list_items as $item) {
    echo '<li>' . esc_html($item) . '</li>';
  }
  echo '</ul>';
  echo '<form method="post">';
  echo '<input type="text" name="cwpai_todo_list_items" style="width:100%;" placeholder="Enter your to-do item">';
  echo '<p><input type="submit" value="Save To-Do List" class="button-primary"></p>';
  echo '</form>';
}
Next, we create a function cwpai_display_todo_list_widget
to handle the widget content.Â
This code saves new to-do items you enter and displays them as a list. When you submit a new item, it sanitizes the input by running the sanitize_text_field
function to remove unwanted or potentially harmful characters.Â
The sanitized input is stored in the $new_item
variable. The function then adds the new item to the list and updates the saved options. The widget shows all saved items and includes a form to add more.
Add Style to the Widget
function cwpai_todo_list_widget_css() {
  echo '<style>
    #cwpai_todo_list_widget ul {
      list-style-type: disc;
      padding-left: 20px;
    }
    #cwpai_todo_list_widget input[type="text"] {
      margin-top: 10px;
      padding: 8px;
      font-size: 14px;
      box-sizing: border-box;
    }
    #cwpai_todo_list_widget input.button-primary {
      margin-top: 10px;
    }
  </style>';
}
add_action('admin_head', 'cwpai_todo_list_widget_css');
This code adds custom CSS to style the to-do list widget. It targets the list, text input, and submit button within the widget. It basically adjusts the margin, padding, font size, and border box-sizing.
The cwpai_todo_list_widget_css
function outputs this CSS, and the add_action('admin_head', 'cwpai_todo_list_widget_css')
line ensures it's added to the admin head section.Â
Step 2: Add the Code to Your Theme’s functions.php
File
Copy and paste the code above into your theme's functions.php
file. This file is usually found in wp-content/themes/your-theme-name/functions.php
.
Note: You can enqueue the CSS separately for better organization.
Step 3: Check the Widget in the WordPress Dashboard
Once you've added the code, go to your WordPress dashboard. You should now see a widget titled Admin To-Do List with a form to add and display to-do items.
More Complex Example: Creating a Chart Widget
Let's take our widget creation skills up a notch by building a more sophisticated dashboard element - a Chart Widget.
This tool is useful for website owners and managers who need to keep a close eye on user engagement and growth patterns. Instead of digging through reports or external analytics tools, you'll have key metrics available at a glance every time you log into your WordPress admin area.
Our goal is to display user growth data in a simple, easy-to-understand graph. We’ll use the popular Chart.js
library to visualize the growth trends.
Here’s how we do it:
Step 1: Register the widget using wp_add_dashboard_widget
First, let's add our new Chart Widget to the WordPress dashboard. We'll use the wp_add_dashboard_widget
function to register our widget. This function assigns a unique identifier and a title to our widget.
Code:
function cwpai_register_chart_widget() {
  wp_add_dashboard_widget(
    'chart_widget',
    'User Growth Chart',
    'cwpai_display_chart_widget'
  );
}
add_action('wp_dashboard_setup', 'cwpai_register_chart_widget');
In this code, we've set up a function called cwpai_register_chart_widget()
to add our dashboard widget titled User Growth Chart. It uses wp_add_dashboard_widget
to register and display the widget’s content. This setup is triggered during the WordPress dashboard setup with add_action('wp_dashboard_setup', 'cwpai_register_chart_widget')
.
Step 2: Create the callback function to display a chart
Now, let's make a callback function that fetches user growth data and gets it ready to show in a chart.
For this example, we're using dummy data. Here's how we set it up:
function cwpai_get_user_growth_data() {
  $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  $growth_data = [];
  foreach ($months as $month) {
    $growth_data[$month] = rand(50, 200);
  }
  return $growth_data;
}
This code generates mock user growth data for each month of the year. It creates an array of months and assigns a random number of users (between 50 and 200) to each month. The function then returns this data as an associative array where each month is a key and the corresponding user count is the value.
Note that you can use any plugin to obtain real user growth data. Examples include MonsterInsights, Google Analytics Dashboard for WordPress, and WP Statistics. You’ll need to review the functions or methods provided by your selected plugin to fetch user growth data.Â
Once you have the data, use the following code to display the chart:
function cwpai_display_chart_widget() {
  $user_growth_data = cwpai_get_user_growth_data();
  $months = json_encode(array_keys($user_growth_data));
  $values = json_encode(array_values($user_growth_data));
  wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js', [], null, true);
  echo '<canvas id="userGrowthChart" width="400" height="200"></canvas>';
  ?>
  <script>
    document.addEventListener('DOMContentLoaded', function () {
      var ctx = document.getElementById('userGrowthChart').getContext('2d');
      var chart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: <?php echo $months; ?>,
          datasets: [{
            label: 'User Growth',
            data: <?php echo $values; ?>,
            borderColor: 'rgba(75, 192, 192, 1)',
            backgroundColor: 'rgba(75, 192, 192, 0.2)',
            borderWidth: 1
          }]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    });
  </script>
  <?php
}
?>
The cwpai_display_chart_widget
function retrieves user growth data and uses the Chart.js
library to render the chart. The script then creates a line chart on the WordPress dashboard canvas which shows user growth trends over months. The chart is customized with labels, data points, colors, and scales for a clear visualization of user growth trends.
Step 3: Use Chart.js
to Render the Chart
Now, let’s enqueue the Chart.js
script using wp_enqueue_script
to load the library from a CDN. It’s hooked to the admin_enqueue_scripts
action to ensure it’s loaded exclusively in the admin area.
// Enqueue Chart.js
function enqueue_chart_js() {
  wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js', [], null, true);
}
add_action('admin_enqueue_scripts', 'enqueue_chart_js');
Step 4: Add the code to your theme’s functions.php
file
Copy and paste all the provided code snippets into your theme’s functions.php
file. This includes registering the widget, creating the callback function, fetching data, and enqueuing scripts.
Here’s the final code we’ve put together:
// Register the chart widget
function register_chart_widget() {
  wp_add_dashboard_widget(
    'chart_widget',     // Widget slug
    'User Growth Chart',   // Title
    'display_chart_widget'  // Display function
  );
}
add_action('wp_dashboard_setup', 'register_chart_widget');
// Fetch user growth data (example function)
function get_user_growth_data() {
  // Example data retrieval; replace with actual plugin data fetching logic
  return [
    'January' => 50,
    'February' => 75,
    'March' => 100,
    'April' => 150,
    'May' => 200,
  ];
}
// Display the chart widget content
function display_chart_widget() {
  $user_growth_data = get_user_growth_data();
  $months = json_encode(array_keys($user_growth_data));
  $values = json_encode(array_values($user_growth_data));
  // Enqueue Chart.js
  wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js', [], null, true);
  // Display the chart using a canvas element
  echo '<canvas id="userGrowthChart" width="400" height="200"></canvas>';
  ?>
  <script>
    document.addEventListener('DOMContentLoaded', function () {
      var ctx = document.getElementById('userGrowthChart').getContext('2d');
      var chart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: <?php echo $months; ?>,
          datasets: [{
            label: 'User Growth',
            data: <?php echo $values; ?>,
            borderColor: 'rgba(75, 192, 192, 1)',
            backgroundColor: 'rgba(75, 192, 192, 0.2)',
            borderWidth: 1
          }]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    });
  </script>
  <?php
}
Step 5: Verify the widget and chart appear in the WordPress dashboard
After adding the code to your theme's functions.php
file, go to your WordPress dashboard. You should see a new widget titled User Growth Chart displaying a line chart with user growth data month over month.
That’s It!
You've just learned how to create your own WordPress dashboard widget. Time to put your skills into action!
Start by experimenting with simple widgets, like the to-do list we created. Then, challenge yourself with more complex designs by creating something similar to the user growth chart. Create widgets that solve real problems for you or your clients. Think about what information or tools would be most useful in your daily WordPress management, and build widgets to match those needs.
Have fun customizing, and enjoy the enhanced functionality your widgets bring to your sites!