How to Display Logged Users Avatar in BuddyPress

Home » Snippets » How to Display Logged Users Avatar in BuddyPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you looking to enhance the user experience on your BuddyPress community website? One way to do that is by displaying the avatars of logged-in users. Avatars can help users identify each other and add a personal touch to their profiles. In this article, we will guide you through the process of displaying logged-in users’ avatars on your BuddyPress website, helping you create a more engaging and visually appealing community.

					function wpturbo_display_logged_user_avatar() {
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        $avatar = bp_core_fetch_avatar(array(
            'item_id' => $user_id,
            'type' => 'thumb',
            'html' => false
        ));
        echo $avatar;
    }
}
add_action('wp_footer', 'wpturbo_display_logged_user_avatar');
				

The code snippet provided above is used to display the avatar of the currently logged-in user on a WordPress website with the BuddyPress plugin activated.

Let’s break down the snippet and understand how it works.

First, we define a function called wpturbo_display_logged_user_avatar(). This function will be responsible for retrieving the user’s avatar and displaying it on the website.

Inside the function, we check if the user is logged in using the is_user_logged_in() function. This ensures that the avatar is only displayed for logged-in users.

Next, we retrieve the user ID of the current user using the get_current_user_id() function. This user ID is required to fetch the avatar.

We then use the bp_core_fetch_avatar() function provided by the BuddyPress plugin to fetch the avatar. The bp_core_fetch_avatar() function accepts an array of parameters to customize the avatar output. In this case, we set the item_id parameter to the user ID we retrieved earlier, specify the type of avatar as ‘thumb’ (thumbnail size), and set the html parameter to false to return the avatar URL instead of HTML markup.

The bp_core_fetch_avatar() function returns the avatar URL, which we assign to the $avatar variable.

Finally, we use the echo statement to output the $avatar variable, which displays the avatar on the website.

To ensure that the function is executed and the avatar is displayed, we hook the wpturbo_display_logged_user_avatar() function to the wp_footer action. The wp_footer action is triggered when the footer of the website is being rendered.

By adding this snippet to your WordPress website and customizing the avatar parameters as needed, you can display the avatar of the currently logged-in user using BuddyPress.

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