get the avatar url instead of an html img tag when using get_avatar?

i want to get the user avatar URL to use it as background URL style for a div. i tried to use the following but it does not return anything when i view the code it appears like that.

background: url()

i used this function.

Read More
function get_avatar_url($get_avatar){
preg_match("/src='(.*?)'/i", $get_avatar, $matches);
return $matches[1];
}

any help please??

Related posts

Leave a Reply

3 comments

  1. It’s fairly simple to construct the Gravatar URL yourself, it’s just an MD5 hash of the user’s email address.

    <?php $gravatar = 'http://www.gravatar.com/avatar/' . md5(strtolower($email)) . '&s=32'; ?>
    
    <div class="avatar" style="background: url(<?php echo $gravatar ?>);" ></div>
    

    The s parameter at the end there defines the size of the image in pixels.

    Using GravatarsWordPress Codex

  2. <?php
    add_filter(
        'get_avatar',
        'get_avatar_url',
        10,
        5
    );
    
    function get_avatar_url( $avatar, $id_or_email, $size = 96, $default = '', $alt = '' ) {
    
        preg_match( '#src=["|'](.+)["|']#Uuis', $avatar, $matches );
    
        return ( isset( $matches[1] ) && ! empty( $matches[1]) ) ?
            (string) $matches[1] : '';  
    
    }
    

    Apply a filter on get_avatar, it takes 5 arguments (!). The first one is the complete <img>-tag. And do not forget the source can be enclosed with double and single quotes ( ["|'] ). I guess that was the point where your function failed.

  3. As of WordPress version 4.2.0, we can use get_avatar_url(). The function can be found in wp-includes/link-template.php:

    function get_avatar_url( $id_or_email, $args = null ) {
        $args = get_avatar_data( $id_or_email, $args );
        return $args['url'];
    }
    

    So you can simply use it by:

    $avatar_url = get_avatar_url($user_id);
    

    Also, I know this is an old question, but a great lesson to be learned. Always use prefixes when you add your custom functions. Your custom function is get_avatar_url() and so is the newly added core function get_avatar_url(). You would have received an error when you upgraded to 4.2.0.