count_user_posts() WordPress Function

The count_user_posts() function is used to get the number of posts a user has written.

count_user_posts( int $userid, array|string $post_type = 'post', bool $public_only = false ) #

Gets the number of posts a user has written.


Parameters

$userid

(int)(Required)User ID.

$post_type

(array|string)(Optional) Single post type or array of post types to count the number of posts for.

Default value: 'post'

$public_only

(bool)(Optional) Whether to only return counts for public posts.

Default value: false


Top ↑

Return

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


Top ↑

Source

File: wp-includes/user.php

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


Top ↑

Changelog

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

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More