Skip to content

Instantly share code, notes, and snippets.

@dwanjuki
Created November 28, 2024 08:50
Show Gist options
  • Save dwanjuki/9d14b2b5bcdd8ee9dccb4c96ac0891e8 to your computer and use it in GitHub Desktop.
Save dwanjuki/9d14b2b5bcdd8ee9dccb4c96ac0891e8 to your computer and use it in GitHub Desktop.
Filter the output of the the get_avatar_url function to use our local avatar
<?php
/**
* Filter the output of the the get_avatar_url function to use our local avatar
*
* Guide: https://www.paidmembershipspro.com/custom-user-avatars-member-profile-edit-page/
*
* You can add this recipe to your site by creating a custom plugin
* or using the Code Snippets plugin available for free in the WordPress repository.
* Read this companion article for step-by-step directions on either method.
* https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/
*/
function my_custom_get_avatar_url( $url, $id_or_email, $args ) {
if ( is_numeric( $id_or_email ) ) {
$user_id = $id_or_email;
} elseif ( is_email( $id_or_email ) ) {
$user = get_user_by( 'email', $id_or_email );
$user_id = $user->ID;
} elseif ( is_object( $id_or_email ) && ! empty( $id_or_email->ID ) ) {
$user_id = $id_or_email->ID;
}
if ( empty( $user_id ) ) {
return $url;
}
$avatar_id = get_user_meta( $user_id, 'wp_user_avatar', true );
if ( ! empty( $avatar_id ) ) {
$avatar = wp_get_attachment_image_src( $avatar_id );
if ( $avatar ) {
$url = $avatar[0];
}
}
return $url;
}
add_filter( 'get_avatar_url', 'my_custom_get_avatar_url', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment