Last active
September 2, 2022 19:11
-
-
Save mennwebs/0269133ec22b2410274828a37129330e to your computer and use it in GitHub Desktop.
Use ACF image field as avatar
This file contains hidden or 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
| <?php | |
| /** | |
| * Use ACF image field as avatar | |
| * @author Mike Hemberger | |
| * @link http://thestizmedia.com/acf-pro-simple-local-avatars/ | |
| * @uses ACF Pro image field (tested return value set as Array ) | |
| */ | |
| add_filter('get_avatar', 'acf_profile_avatar', 10, 5); | |
| function acf_profile_avatar( $avatar, $id_or_email, $size, $default, $alt ) { | |
| 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; | |
| } | |
| $user_id = $user->ID; | |
| $image_id = get_user_meta($user_id, 'avatar', true); // CHANGE TO YOUR FIELD NAME | |
| if ( ! $image_id ) { | |
| return $avatar; | |
| } | |
| $image_url = wp_get_attachment_image_src( $image_id, 'thumbnail' ); // Set image size by name | |
| $avatar_url = $image_url[0]; | |
| $avatar = '<img alt="' . $alt . '" src="' . $avatar_url . '" class="avatar avatar-' . $size . '" height="' . $size . '" width="' . $size . '">'; | |
| return $avatar; | |
| } | |
| add_filter('get_avatar_url', 'acf_profile_avatar_url', 10, 3); | |
| function acf_profile_avatar_url($url, $id_or_email, $args){ | |
| 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 $url; | |
| } | |
| $user_id = $user->ID; | |
| $image_id = get_user_meta($user_id, 'avatar', true); // CHANGE TO YOUR FIELD NAME | |
| if ( ! $image_id ) { | |
| return $url; | |
| } | |
| $image_url = wp_get_attachment_image_src( $image_id, 'thumbnail' ); // Set image size by name | |
| $avatar_url = $image_url[0]; | |
| return $avatar_url; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment