As WordPress developers we know how powerful and flexible it is, one of the feature that allows us to streamline our workflows and improve user experience is the WordPress dashboard. By customizing the dashboard with widgets we can have users have quick access to various information and tasks.

What are Dashboard Widgets?

Dashboard widgets are small, customizable modules that appear on the WordPress admin screen. These widgets provide essential information about the various aspects of the site. The default WordPress dashboard comes with several built-in widgets, such as “At a Glance,” “Recent Drafts,” and “Quick Draft,” but as WordPress users, we can also add custom widgets to suit our needs.

How to Add Custom Widgets to Your WordPress Dashboard

Inside our plugin we can add Custom Dashboard widgets using the wp_add_dashboard_widget()

function custom_dashboard_widget() {
    wp_add_dashboard_widget(
        'custom_dashboard_widget', // Widget slug
        'My Custom Widget',        // Widget title
        'custom_dashboard_widget_html' // Function to display widget
    );
}

function custom_dashboard_widget_html() {
    echo '<p>This is a custom dashboard widget</p>';
}

add_action('wp_dashboard_setup', 'custom_dashboard_widget');

The wp_add_dashboard_widget() function takes in a widget slug, title, and a callback function to display the widget.

Similar to this we can add more advanced features to it as well.

Exampleโ€” “Widget for fetching the latest posts from a blog.”

function latest_posts_dashboard_widget() {
    wp_add_dashboard_widget(
        'latest_posts_dashboard_widget',
        'Latest Posts',                  
        'latest_post_dashboard_widget_html'
    );
}

function latest_post_dashboard_widget_html() {
    $args = array(
        'posts_per_page' => 5,
        'post_status'    => 'publish',
        'order'           => 'DESC',
        'orderby'         => 'date',
    );
    
    $query = new WP_Query($args);

    if ($query->have_posts()) {
        echo '<ul>';
        
        while ($query->have_posts()) {
            $query->the_post();
            echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
        
        echo '</ul>';
    } else {
        echo '<p>No recent posts found.</p>';
    }
    
    wp_reset_postdata();
}

add_action('wp_dashboard_setup', 'latest_posts_dashboard_widget');

Conclusion

Dashboard Widgets are one of the simplest and powerful way to customize and enhance the WP Admin interface. They provide us with quick access to important information, boost our productivity, and help streamline our workflows. Whether we’re managing a personal blog, running an e-commerce store, or handling multiple client websites, taking full advantage of dashboard widgets can make our jobs much easier.

Leave a Reply

Your email address will not be published. Required fields are marked *