| 1 | <?php |
|---|
| 2 | |
|---|
| 3 | /** |
|---|
| 4 | * Replace default WordPress avatars URL with BP avatars URL, if available. |
|---|
| 5 | * |
|---|
| 6 | * See 'get_avatar_url' filter description in wp-includes/pluggable.php. |
|---|
| 7 | * |
|---|
| 8 | * @param string $url The avatar path passed to 'get_avatar'. |
|---|
| 9 | * @param int|string|object $id_or_email A user ID, email address, or comment object. |
|---|
| 10 | * @param array $args Arguments passed to get_avatar_data(), after processing. |
|---|
| 11 | * @return string BP avatar URL, if found; else the original avatar URL. |
|---|
| 12 | */ |
|---|
| 13 | function bp_fetch_avatar_url_filter( $url, $id_or_email, $args ) { |
|---|
| 14 | /** |
|---|
| 15 | * Remove this filter to prevent infinite loop as |
|---|
| 16 | * get_avatar itself calls get_avatar_url |
|---|
| 17 | */ |
|---|
| 18 | remove_filter('get_avatar_url', __FUNCTION__, 11, 3); |
|---|
| 19 | |
|---|
| 20 | // get avatar HTML |
|---|
| 21 | $avatar_html = call_user_func_array('get_avatar', array( |
|---|
| 22 | $id_or_email, |
|---|
| 23 | isset($args['size']) ? esc_attr($args['size']) : null, |
|---|
| 24 | isset($args['default']) ? esc_attr($args['default']) : null, |
|---|
| 25 | null, |
|---|
| 26 | $args |
|---|
| 27 | )); |
|---|
| 28 | |
|---|
| 29 | /** |
|---|
| 30 | * Restore back the filter now that we got the avatar HTML |
|---|
| 31 | */ |
|---|
| 32 | add_filter('get_avatar_url', __FUNCTION__, 11, 3); |
|---|
| 33 | |
|---|
| 34 | /** Search for image src attribute // regex might need improvement **/ |
|---|
| 35 | preg_match('/<img\s*(.*?) src=["\']?(.*?)["\']? (.*?)>/si', $avatar_html, $src); |
|---|
| 36 | |
|---|
| 37 | /** assign the image src as the avatar URL **/ |
|---|
| 38 | if ( !empty( $src[2] ) ) { |
|---|
| 39 | $url = esc_url( $src[2] ); |
|---|
| 40 | } |
|---|
| 41 | |
|---|
| 42 | /** the new avatar URL, bp filtered **/ |
|---|
| 43 | return $url; |
|---|
| 44 | } |
|---|
| 45 | add_filter( 'get_avatar_url', 'bp_fetch_avatar_url_filter', 11, 3 ); |
|---|