WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/count user posts

Description

Returns the post count for a user.

Usage

<?php $user_post_count count_user_posts$userid $post_type ); ?>

Parameters

$userid
(integer) (required) The ID of the user to count posts for.
Default: None
$post_type
(string) (optional) Post type to count the number of posts for.
Default: "post"

Returns

(int)
Number of posts the user has written in this post type..

Examples

Get post count for a user

Display the number of posts published by the user with an ID of 5.

<?php echo 'Number of posts published by user: ' . count_user_posts( 5 ); ?>

Get post count for a user of post type

Display the number of posts of post type "book" published by the user with an ID of 5.

<?php echo 'Number of posts published by user: ' . count_user_posts( 5 , "book"  ); ?>

Translation friendly post count

The same operation, with translation support.

<?php printf( __( 'Number of posts published by user: %d', 'text-dom-here' ), count_user_posts( 5 ) ); ?>

Result

The result of the above two examples

Number of posts published by user: 123

Support for other post types

Note : Since 4.1 it supports post types.
As post_type support is not currently available for count_user_posts(), below you will find a derivative function with post_type support provided via a secondary parameter.

<?php
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 );
}
?>

Change Log

  • Since: 3.0.0
  • Since: 4.1.0 (Added post type support)

Source File

count_user_posts() is located in wp-includes/user.php.

Related

count_many_users_posts, get_posts_by_author_sql

See also index of Function Reference and index of Template Tags.