Using WordPress ‘count_user_posts()’ PHP function

The count_user_posts() WordPress PHP function retrieves the number of posts written by a specific user.

Usage

count_user_posts( $userid, $post_type = 'post', $public_only = false );

In this example, the function checks the number of posts authored by the user with an ID of 3. The output would be an integer representing the total number of posts.

$total_posts = count_user_posts( 3 );
echo 'Total posts by the user: ' . $total_posts;

Parameters

  • $userid (int): The user ID. This is a required parameter.
  • $post_type (array|string): The type of posts to count. It can either be a single post type or an array of post types. The default is ‘post’.
  • $public_only (bool): Whether to count only public posts. The default is false, meaning both public and private posts are counted.

More Information

See WordPress Developer Resources: count_user_posts()

Note: Private posts are included in the count when $public_only is set to false. Posts with ‘trash’ status or custom status are not included.

Examples

Counting All Posts by a User

This code counts all posts (public and private) written by the user with an ID of 1.

$total_posts = count_user_posts( 1 );
echo 'Total posts by the user: ' . $total_posts;

Counting Specific Post Types by a User

This example counts the number of ‘book’ posts authored by the user with an ID of 2.

$total_posts = count_user_posts( 2, 'book' );
echo 'Total book posts by the user: ' . $total_posts;

Counting Multiple Post Types by a User

In this case, we’re counting ‘post’ and ‘page’ types for the user with an ID of 3.

$total_posts = count_user_posts( 3, array('post', 'page') );
echo 'Total posts and pages by the user: ' . $total_posts;

Counting Only Public Posts by a User

This code checks the number of public posts authored by the user with an ID of 4.

$total_posts = count_user_posts( 4, 'post', true );
echo 'Total public posts by the user: ' . $total_posts;

Counting Posts with Translation Support

This example demonstrates how to count user’s posts with translation support.

$total_posts = count_user_posts( 5 );
printf( __( 'Number of posts published by user: %d', 'wpdocs_textdomain' ), $total_posts );