Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

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

any help please??

share|improve this question
2  
Where is the $get_avatar variable coming from? –  Joseph Aug 27 '12 at 12:42
add comment

2 Answers

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 Gravatars - WordPress Codex

share|improve this answer
add comment
<?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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.