count_many_users_posts()WP 3.0.0

Number of posts written by a list of users.

No Hooks.

Return

String[]. Amount of posts each user has written, as strings, keyed by user ID.

Usage

count_many_users_posts( $users, $post_type, $public_only );
$users(int[]) (required)
Array of user IDs.
$post_type(string|string[])
Single post type or array of post types to check.
Default: 'post'
$public_only(true|false)
Only return counts for public posts.
Default: false

Examples

0

#1 How to get the number (count) of users posts

$users = [ 1, 141 ];
$counts = count_many_users_posts( $users );

print_r( $counts );

/*
Array (
	[1] => 157
	[141] => 15
)
*/

Notes

  • Global. wpdb. $wpdb WordPress database abstraction object.

Changelog

Since 3.0.0 Introduced.

count_many_users_posts() code WP 6.5.2

function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
	global $wpdb;

	$count = array();
	if ( empty( $users ) || ! is_array( $users ) ) {
		return $count;
	}

	$userlist = implode( ',', array_map( 'absint', $users ) );
	$where    = get_posts_by_author_sql( $post_type, true, null, $public_only );

	$result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
	foreach ( $result as $row ) {
		$count[ $row[0] ] = $row[1];
	}

	foreach ( $users as $id ) {
		if ( ! isset( $count[ $id ] ) ) {
			$count[ $id ] = 0;
		}
	}

	return $count;
}