Back to Snippets

Custom Admin Dashboard Widget

PHP Admin & Dashboard April 6, 2026

Add a custom WordPress admin dashboard widget showing post type stats and recent entries. Clean, escaped output with proper i18n.

Snippet Stats

Lines 44
Characters 1,390
Read 2 mins
php • 44 lines
/**
 * Add a custom dashboard widget showing recent snippet stats.
 */
add_action( 'wp_dashboard_setup', function(): void {
    wp_add_dashboard_widget(
        'ifci_snippet_stats',
        __( 'Snippet Library Stats', 'theme-domain' ),
        'ifci_render_stats_widget'
    );
} );

function ifci_render_stats_widget(): void {
    $total    = wp_count_posts( 'ifci_snippet' );
    $published = isset( $total->publish ) ? absint( $total->publish ) : 0;

    $categories = wp_count_terms( array(
        'taxonomy'   => 'ifci_snippet_cat',
        'hide_empty' => false,
    ) );

    $recent = get_posts( array(
        'post_type'      => 'ifci_snippet',
        'posts_per_page' => 5,
        'orderby'        => 'date',
        'order'          => 'DESC',
    ) );

    echo '' . esc_html__( 'Total Snippets:', 'theme-domain' ) . ' ' . esc_html( (string) $published ) . '';
    echo '' . esc_html__( 'Categories:', 'theme-domain' ) . ' ' . esc_html( (string) $categories ) . '';

    if ( $recent ) {
        echo '' . esc_html__( 'Recently Added', 'theme-domain' ) . '';
        echo '';
        foreach ( $recent as $post ) {
            printf(
                '%s — %s',
                esc_url( get_edit_post_link( $post->ID ) ),
                esc_html( $post->post_title ),
                esc_html( get_the_date( '', $post ) )
            );
        }
        echo '';
    }
}

Found an issue with this snippet? Help us improve by reporting it. Report it →

Related Snippets

View all
JavaScript
This reusable Higher Order Component handles asynchronous data fetching in React applications, making it ideal for fetching data from APIs on componen...

React Higher Order Component For Asynchronous Data Fetching And Error Handling

JavaScript
This React code snippet demonstrates a centralized global state management pattern using the Context API, simplifying state access and updates across ...

React Context API Pattern For Managing Global State In Large-Scale Applications

PHP
This code snippet provides a custom WordPress hook to update user profiles. It is useful when you need to synchronize user data with external services...

WordPress Custom Hook For User Profile Updates