How to Display User Comment Count Next to Username in WordPress

Home » Snippets » How to Display User Comment Count Next to Username in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Do you run a website that relies on user engagement to drive traffic and conversation? If so, you may want to consider displaying user comment counts next to their usernames. This can add a layer of gamification to your website, encouraging users to engage even more with your content. In this article, we’ll show you how to display user comment counts next to usernames in your WordPress site.

					function wpturbo_display_user_comment_count( $username ) {
    $user = get_user_by( 'login', $username );
    $comment_count = get_comments( array(
        'user_id' => $user->ID,
        'count' => true
    ) );
    echo '<span class="wpturbo-user-comment-count">' . sprintf( __( '%s Comments', 'wpturbo' ), $comment_count ) . '</span>';
}

add_action( 'bp_member_header_meta', 'wpturbo_display_user_comment_count' );
				

The code snippet above shows how to add the comment count next to the username of each user on a BuddyPress network. It does so by creating a function called wpturbo_display_user_comment_count() and then hooking this function into the bp_member_header_meta action.

First, we create a new function called wpturbo_display_user_comment_count() that takes $username as a parameter. Inside the function, we retrieve the user object for the given username by using the get_user_by() function. This function returns a WP_User object that we can use to get other information about the user, such as their ID.

Next, we use get_comments() function to retrieve an array of comments associated with the user whose username was passed to the function. We specify the 'user_id' parameter to retrieve only the comments made by that user, and set the 'count' parameter to true so we get the total comment count for that user.

Now, we have the comment count for the user. We use echo to output the comment count inside a span element with a class of wpturbo-user-comment-count. We use the sprintf() function to format the comment count string. This function enables us to replace the "%s" substring in the string with the actual comment count. And finally, we close the span element.

Finally, we add our wpturbo_display_user_comment_count() function to the bp_member_header_meta action. This action is called on the BuddyPress member profile page, and our function will be called each time the action is fired. Once added, the user comment count will be displayed next to the username of each member on the BuddyPress network.

Register an account to save your snippets or go Pro to get more features.