Using WordPress ‘get_user_count()’ PHP function

The get_user_count() WordPress PHP function returns the number of active users in your installation.

Usage

To get the number of active users and display a message:

$user_count = get_user_count();
echo "There are currently $user_count users on this site.";

Parameters

  • $network_id (int|null): Optional ID of the network. Defaults to the current network. Default: null

More information

See WordPress Developer Resources: get_user_count()

Examples

Display User Count in Dashboard Widget

Create a dashboard widget to display the user count:

function display_user_count_dashboard_widget() {
  $user_count = get_user_count();
  echo "<strong>There are currently $user_count users on this site.</strong>";
}

function register_user_count_dashboard_widget() {
  wp_add_dashboard_widget(
    'user_count_dashboard_widget',
    'User Count',
    'display_user_count_dashboard_widget'
  );
}
add_action('wp_dashboard_setup', 'register_user_count_dashboard_widget');

Display User Count in Admin Bar

Add the user count to the admin bar:

function add_user_count_to_admin_bar($wp_admin_bar) {
  $user_count = get_user_count();
  $wp_admin_bar->add_node(array(
    'id' => 'user_count',
    'title' => "Users: $user_count"
  ));
}
add_action('admin_bar_menu', 'add_user_count_to_admin_bar', 100);

Display User Count in a Shortcode

Create a shortcode to display the user count:

function user_count_shortcode() {
  $user_count = get_user_count();
  return "There are currently $user_count users on this site.";
}
add_shortcode('user_count', 'user_count_shortcode');

Usage: [user_count]

Display User Count in a Widget

Create a widget to display the user count:

class User_Count_Widget extends WP_Widget {
  function __construct() {
    parent::__construct(
      'user_count_widget',
      'User Count',
      array('description' => 'Displays the number of active users')
    );
  }

  function widget($args, $instance) {
    $user_count = get_user_count();
    echo $args['before_widget'];
    echo $args['before_title'] . 'User Count' . $args['after_title'];
    echo "<strong>There are currently $user_count users on this site.</strong>";
    echo $args['after_widget'];
  }
}
add_action('widgets_init', function() {
  register_widget('User_Count_Widget');
});

Display User Count in a Gutenberg Block

Register a Gutenberg block to display the user count:

function register_user_count_block() {
  wp_register_script(
    'user-count-block',
    plugins_url('block.js', __FILE__),
    array('wp-blocks', 'wp-element')
  );

  register_block_type('custom/user-count', array(
    'editor_script' => 'user-count-block'
  ));
}
add_action('init', 'register_user_count_block');

In block.js:

const { registerBlockType } = wp.blocks;

registerBlockType('custom/user-count', {
  title: 'User Count',
  icon: 'admin-users',
  category: 'common',
  edit: () => {
    return <p>Loading user count...</p>;
  },
  save: () => {
    return null;
  }
});