WordPress at a glance

count_user_posts() WP 3.0.0

Returns the number of posts that belong to the user.

If you want to get the number of posts of multiple users, use count_many_users_posts().

Works based on: get_posts_by_author_sql()
1 time = 0.001945s = very slow | 50000 times = 46.58s = very slow | PHP 7.1.2, WP 4.7.3
Hooks from the function

String. Number of posts the user has written in this post type.


count_user_posts( $userid, $post_type, $public_only );
$userid(int) (required)
User ID.
Single post type or array of post types to count the number of posts for.
Default: 'post'
Whether to only return counts for public posts.
Default: false


#1 Get the number of posts of the user

Show how many posts belong to (were written by) the user with ID 1.

<?php echo 'Total posts: ' . count_user_posts(1); ?>

Output: Total posts: 321

#2 Show the number of posts of the book type that belong to the user

Suppose that we have a book post type and we want to find out how many posts of this type belong to the user with ID 5:

<?php echo 'The user 5 has published ' . count_user_posts( 5, 'book') . ' books.'; ?>

#3 Support for the custom posts type (for WP prior to 4.1 version)

This example is only useful for WP versions prior to 4.1 version where this function doesn't have a second ($post_type) parameter.

We will create a custom function for these purposes: the first parameter for the user ID, the second for the post type.

function count_user_posts_by_type($userid, $post_type='post') {
  global $wpdb;
  $where = get_posts_by_author_sql( $post_type, TRUE, $userid );
  $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
  return apply_filters('get_usernumposts', $count, $userid);


  • Since 4.1 version this function has a second ($post_type) parameter to specify the post type to count the number of posts for.


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


Since 3.0.0 Introduced.
Since 4.1.0 Added $post_type argument.
Since 4.3.0 Added $public_only argument. Added the ability to pass an array of post types to $post_type.

Code of count_user_posts() WP 5.6

function count_user_posts( $userid, $post_type = 'post', $public_only = false ) {
	global $wpdb;

	$where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );

	$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );

	 * Filters the number of posts a user has written.
	 * @since 2.7.0
	 * @since 4.1.0 Added `$post_type` argument.
	 * @since 4.3.1 Added `$public_only` argument.
	 * @param int          $count       The user's post count.
	 * @param int          $userid      User ID.
	 * @param string|array $post_type   Single post type or array of post types to count the number of posts for.
	 * @param bool         $public_only Whether to limit counted posts to public posts.
	return apply_filters( 'get_usernumposts', $count, $userid, $post_type, $public_only );

From category: Other

No comments
    Log In