Halloween Sale 15% off Ends in See the plans
PHP

Paid Memberships Pro: Members per Level Dashboard Widget

Adds a dashboard widget that lists your membership levels with the number of active members in each, cached so the dashboard stays fast.

Don’t have WPIDE yet? Install it on your site

Code

if ( ! function_exists( 'pmpro_getAllLevels' ) ) {
    return;
}

add_action( 'wp_dashboard_setup', function () {
    if ( ! current_user_can( 'pmpro_memberslist' ) && ! current_user_can( 'manage_options' ) ) {
        return;
    }

    wp_add_dashboard_widget( 'wpide_pmpro_levels', 'Members per level', function () {
        global $wpdb;

        $counts = get_transient( 'wpide_pmpro_level_counts' );

        if ( false === $counts ) {
            $rows   = $wpdb->get_results( "SELECT membership_id, COUNT(DISTINCT user_id) AS total FROM {$wpdb->pmpro_memberships_users} WHERE status = 'active' GROUP BY membership_id" );
            $counts = wp_list_pluck( (array) $rows, 'total', 'membership_id' );
            set_transient( 'wpide_pmpro_level_counts', $counts, HOUR_IN_SECONDS );
        }

        echo '<table class="widefat striped"><thead><tr><th scope="col">Level</th><th scope="col">Active members</th></tr></thead><tbody>';

        foreach ( pmpro_getAllLevels( true ) as $level ) {
            printf( '<tr><td>%1$s</td><td>%2$s</td></tr>', esc_html( $level->name ), esc_html( number_format_i18n( (int) ( $counts[ $level->id ] ?? 0 ) ) ) );
        }

        echo '</tbody></table>';
        printf( '<p><a href="%s">View members</a></p>', esc_url( admin_url( 'admin.php?page=pmpro-memberslist' ) ) );
    } );
} );

add_action( 'pmpro_after_change_membership_level', function () {
    delete_transient( 'wpide_pmpro_level_counts' );
} );

Notes

Counts refresh every hour and whenever a membership changes.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.