The get_usernumposts() WordPress PHP function retrieves the number of posts a user has written.
Usage
$total_posts = get_usernumposts( $userid );
Parameters
$userid(int) – Required. The user ID for whom you want to count the posts.
More information
See WordPress Developer Resources: get_usernumposts()
Examples
Display total posts for a user
This example displays the total number of posts written by a user with the ID 2.
$userid = 2; $total_posts = get_usernumposts($userid); echo 'User ' . $userid . ' has written ' . $total_posts . ' posts.';
Display posts count for the current user
This example displays the total number of posts written by the currently logged-in user.
$current_user = wp_get_current_user(); $total_posts = get_usernumposts($current_user->ID); echo 'You have written ' . $total_posts . ' posts.';
Display posts count for all users
This example displays the total number of posts written by all users on the website.
$users = get_users();
foreach ($users as $user) {
$total_posts = get_usernumposts($user->ID);
echo 'User ' . $user->display_name . ' has written ' . $total_posts . ' posts.<br>';
}
Display users with more than 10 posts
This example displays the list of users who have written more than 10 posts.
$users = get_users();
foreach ($users as $user) {
$total_posts = get_usernumposts($user->ID);
if ($total_posts > 10) {
echo 'User ' . $user->display_name . ' has written ' . $total_posts . ' posts.<br>';
}
}
Display the total posts for a specific user role
This example displays the total number of posts written by users with the ‘author’ role.
$authors = get_users(array('role' => 'author'));
$total_posts = 0;
foreach ($authors as $author) {
$total_posts += get_usernumposts($author->ID);
}
echo 'Authors have written a total of ' . $total_posts . ' posts.';