Using WordPress ‘count_many_users_posts()’ PHP function

The count_many_users_posts() WordPress PHP function retrieves the number of posts made by a set of users.

Usage

Suppose we have a list of user IDs and we want to find out how many posts each user has made. We can use the count_many_users_posts() function to achieve this.

$users = array( 1, 3, 9, 10 ); 
$counts = count_many_users_posts( $users ); 
echo 'Posts made by user 3: ' . $counts[3]; 

This will output: Posts made by user 3: 143 (assuming user 3 has written 143 posts).

Parameters

  • $users (array): Required. An array of user IDs.
  • $post_type (string|array): Optional. A single post type or array of post types to check. Defaults to ‘post’.
  • $public_only (bool): Optional. If set to true, the function will only return counts for public posts. Defaults to false.

More information

See WordPress Developer Resources: count_many_users_posts()

This function was implemented in WordPress version 3.0.0.

Examples

Count Posts for Multiple Users

Find out how many posts users 1, 2 and 3 have made.

$users = array( 1, 2, 3 ); 
$counts = count_many_users_posts( $users );
foreach ($users as $user) {
    echo 'Posts made by user '.$user.': ' . $counts[$user].'<br>'; 
}

Count Custom Post Types

Find out how many custom posts (let’s say ‘products’) users 1, 2, and 3 have created.

$users = array( 1, 2, 3 );
$counts = count_many_users_posts( $users, 'product');
foreach ($users as $user) {
    echo 'Products created by user '.$user.': ' . $counts[$user].'<br>'; 
}

Count Multiple Post Types

Find out how many ‘post’ and ‘page’ type contents users 1, 2, and 3 have made.

$users = array( 1, 2, 3 );
$post_types = array('post', 'page');
$counts = count_many_users_posts( $users, $post_types );
foreach ($users as $user) {
    echo 'Posts and pages created by user '.$user.': ' . $counts[$user].'<br>'; 
}

Count Public Posts Only

Find out how many public posts users 1, 2, and 3 have made.

$users = array( 1, 2, 3 );
$counts = count_many_users_posts( $users, 'post', true);
foreach ($users as $user) {
    echo 'Public posts made by user '.$user.': ' . $counts[$user].'<br>'; 
}

Count Posts for a Single User

Find out how many posts user 1 has made.

$counts = count_many_users_posts( array(1) );
echo 'Posts made by user 1: ' . $counts[1];