How to Replace BuddyPress Avatar with a Custom One

So i received a question from a customer over at ProfilePress if it was possible for avatars or profile pictures uploaded by users of his website via ProfilePress powered front-end registration and edit profile forms to automatically replace that of BuddyPress.

You know, BuddyPress has its own mechanism for uploading and managing users avatar. Having his website users editing their avatars in two places didn’t quite go down well with him.

So i dug into BuddyPress core and found these two filters: bp_core_fetch_avatar and bp_core_fetch_avatar_url. The former is called when bp_core_fetch_avatar() function is used by BuddyPress to return HTML element of users avatar and the latter when the function returns raw URL of users avatar.

So i wrote the code snippets below utilising the above filters to automatically overrides / replace BuddyPress avatar with that of ProfilePress.

You can easily adapt the code snippet to fit your need.

add_filter( 'bp_core_fetch_avatar', function ( $avatar_img_tag, $params ) {
	
	/** user ID that avatar belongs to. */
	$user_id = absint( $params['item_id'] );

	$custom_avatar_url = get_user_custom_avatar_img_url( $user_id );

	if ( ! empty( $custom_avatar_url ) ) {

		$url = $custom_avatar_url;

		// this simply replace the image url part in the <img> avatar element.
		$avatar_img_tag = preg_replace( '/(<img src=")(.+)(" class.+)/', "$1$url$3", $avatar_img_tag );
	}

	return $avatar_img_tag;

}, 10, 2 );

add_filter( 'bp_core_fetch_avatar_url', function ( $avatar_url, $params ) {

	$user_id = absint( $params['item_id'] );

	$custom_avatar_url = get_user_custom_avatar_img_url( $user_id );

	if ( ! empty( $custom_avatar_url ) ) {
		$avatar_url = $custom_avatar_url;
	}

	return $avatar_url;

}, 10, 2 );

Be sure to let me know in the comments if you found this code snippet useful.

Don’t miss out!
Subscribe to My Newsletter
Invalid email address