When developing a WordPress user center, we often need to get the number of posts and comments created by a user. These two values are used less often, so WordPress does not provide dedicated database columns for them. We can query the data directly with SQL.
Get the number of comments posted by a user
function get_user_comments_count( $user_id ) {
global $wpdb;
$user_id = (int) $user_id;
$sql = "SELECT COUNT(*) FROM {$wpdb->comments} WHERE user_id='$user_id' AND comment_approved = 1";
$coo = $wpdb->get_var( $sql );
return ( $coo ) ? $coo-1: 0;
}
Get the number of articles published by a user
function num_of_author_posts( $user_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;
}
Or you can use an official WordPress function directly:
<?php $user_post_count = count_user_posts( $userid , $post_type ); ?>
The SQL queries above are relatively heavy. If you run them every time you need the post count or comment count, they will create some additional load on the database. To improve performance, you can store the two values as user meta and update them whenever the user publishes a post or a comment. Then you can retrieve them directly with get_user_meta.
