Calculate a User’s Percentage Rank Based on the Number of Posts They Have Published

You have probably seen messages like this before: “Congratulations, your boot speed is faster than 98% of computers.” That was a reminder shown by 360 Boot Assistant. Exactly how that number was calculated is something only the developers of that tool would know. Even so, it is a very simple feature that can do a lot to improve stickiness and encourage user participation. Can we add a similar feature to a social site? Of course. Today I want to introduce a function that calculates a user’s percentage ranking on a site based on the number of articles they have published.

Boot speed ranking example
A boot speed percentage ranking example

Get the number of articles published by a user

/* 获取用户发表的文章数量 */
 function num_of_author_posts( $user_id ){ //根据作者ID获取该作者的文章数量
    global $wpdb;
    $user_id = (int) $user_id;
    $sql = "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_author='$user_id' AND post_status = 'publish' ";
    $coo = $wpdb->get_var( $sql );
    return ( $coo ) ? $coo: 0;
 }

Calculate the user’s percentage ranking from the number of published articles

/*get user post number sort*/
function get_user_sort( $user_id ){

	/*获取所有用户*/
	$users = get_users( array( 'fields' => 'ID') );

	$user_post_num = array();
	foreach ($users as $user) {
		$user_posts = num_of_author_posts($user);
		$user_post_num[next($users)] = $user_posts;
	}

	/* 获取当前用户的文章数量 */
	$current_user_posts = num_of_author_posts( $user_id );

	/*根据文章数量排列用户数组*/
	sort($user_post_num);
	$sort = array_search( $current_user_posts, $user_post_num ); /*user sort*/

	$percent_sort = round( ( ( $sort / (count( $user_post_num ) - 1) ) * 100 ), 0) . '%';
	return $percent_sort;
}

The final effect of the feature above looks something like this:

User ranking percentage example
The user currently ranks ahead of 86% of users

Strictly speaking, this number is not perfectly accurate. In practice, though, it does not need to be perfectly accurate. As long as the user sees a rough percentage that changes when they publish new posts, that is enough to encourage participation and improve activity. If you have a better idea for this feature, feel free to discuss it in the comments.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *