Created
October 14, 2018 23:22
-
-
Save iamandrewpeters/0c6f7bad621a962fb0264a18975a72a9 to your computer and use it in GitHub Desktop.
Use ACF image field as an Avatar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use ACF image field as avatar | |
//Have to create a User image field | |
add_filter('get_avatar', 'acf_profile_avatar', 10, 5); | |
function acf_profile_avatar( $avatar, $id_or_email, $size, $default, $alt ) { | |
// Get user by id or email | |
if ( is_numeric( $id_or_email ) ) { | |
$id = (int) $id_or_email; | |
$user = get_user_by( 'id' , $id ); | |
} elseif ( is_object( $id_or_email ) ) { | |
if ( ! empty( $id_or_email->user_id ) ) { | |
$id = (int) $id_or_email->user_id; | |
$user = get_user_by( 'id' , $id ); | |
} | |
} else { | |
$user = get_user_by( 'email', $id_or_email ); | |
} | |
if ( ! $user ) { | |
return $avatar; | |
} | |
// GetS the user id | |
$user_id = $user->ID; | |
// Get the file id | |
$image_id = get_user_meta($user_id, 'author_profile_picture', true); // CHANGE TO ACF FIELD NAME | |
// Stops if we don't have a local avatar | |
if ( ! $image_id ) { | |
return $avatar; | |
} | |
// File size | |
$image_url = wp_get_attachment_image_src( $image_id, 'thumbnail' ); // Set image size by name | |
// File url | |
$avatar_url = $image_url[0]; | |
// Get the img markup | |
$avatar = '<img alt="' . $alt . '" src="' . $avatar_url . '" class="avatar avatar-' . $size . '" height="' . $size . '" width="' . $size . '">'; | |
// Return our new avatar | |
return $avatar; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment