How to create a custom dashboard widget in WordPress admin

How to create a custom dashboard widget in WordPress admin

Creating a custom dashboard widget in WordPress admin is a great way to add useful information or quick links for users who log in to your site.

Home / Blog / Unspecified / How to create a custom dashboard widget in WordPress admin

Creating a custom dashboard widget in WordPress admin is a great way to add useful information or quick links for users who log in to your site. Here’s how to create a dashboard widget in WordPress admin:

Step 1: Create a function to display your widget content In your theme or plugin’s functions.php file, create a function that will display your widget content. This function should include the HTML and/or PHP code for your widget.

For example:

function my_custom_dashboard_widget() {
    echo '<h2>My Custom Dashboard Widget</h2>';
    echo '<p>This is some example content for my custom dashboard widget.</p>';
}

Step 2: Add the widget to the dashboard using the ‘wp_add_dashboard_widget’ function Next, add your widget to the dashboard using the ‘wp_add_dashboard_widget’ function. This function takes two arguments: a unique ID for your widget, and the function that will display your widget content.

For example:

function my_add_custom_dashboard_widget() {
    wp_add_dashboard_widget(
        'my_custom_dashboard_widget',
        'My Custom Dashboard Widget',
        'my_custom_dashboard_widget'
    );
}
add_action('wp_dashboard_setup', 'my_add_custom_dashboard_widget');

In this example, ‘my_custom_dashboard_widget’ is the unique ID for your widget, ‘My Custom Dashboard Widget’ is the title of your widget, and ‘my_custom_dashboard_widget’ is the function that will display your widget content.

Step 3: Add styles to your widget (optional) If you want to add custom styles to your widget, you can use the ‘wp_add_inline_style’ function to add CSS to the dashboard page.

For example:

function my_add_custom_dashboard_styles() {
    wp_add_inline_style('wp-admin', '
        #my_custom_dashboard_widget {
            background-color: #f5f5f5;
            padding: 10px;
        }
    ');
}
add_action('admin_enqueue_scripts', 'my_add_custom_dashboard_styles');

In this example, we’re adding a background color and padding to the widget.

That’s it! Your custom dashboard widget should now be visible on the WordPress admin dashboard. You can customize the content and styling of your widget to fit your needs.