2

I'm trying to add a custom default avatar to WordPress in functions.php, but the image is not displaying in Settings/Discussion or elsewhere on the site. The code works because a new radio field is added with the custom field name, but the image won't display. Is the avatar not displaying because I'm using Localhost?

I don't have enough reps to comment on similar questions.

here's the code:

add_filter( 'avatar_defaults' , 'wps_new_avatar' );
function wps_new_avatar( $avatar_defaults ){
    $new_avatar = get_stylesheet_directory_uri() . '/images/default-avatar.png';
    $avatar_defaults[$new_avatar] = "Default Avatar";
    return $avatar_defaults;
}

I've tried other examples and the 'Add-New-Default-Avatar' plugin with the same result.

gundam00
  • 45
  • 1
  • 6

1 Answers1

2

I was facing the same issue and came up with this completely hackish solution... It works though :)

add_filter( 'get_avatar', 'so_14088040_localhost_avatar', 10, 5 );

function so_14088040_localhost_avatar( $avatar, $id_or_email, $size, $default, $alt )
{
    $whitelist = array( 'localhost', '127.0.0.1' );

    if( !in_array( $_SERVER['SERVER_ADDR'] , $whitelist ) )
        return $avatar;

    $doc = new DOMDocument;
    $doc->loadHTML( $avatar );
    $imgs = $doc->getElementsByTagName('img');
    if ( $imgs->length > 0 ) 
    {
        $url = urldecode( $imgs->item(0)->getAttribute('src') );
        $url2 = explode( 'd=', $url );
        $url3 = explode( '&', $url2[1] );
        $avatar= "<img src='{$url3[0]}' alt='' class='avatar avatar-64 photo' height='64' width='64' />";
    }

    return $avatar;
}

Result:

localhost avatar


Of course, this filter is meant for development only.

brasofilo
  • 25,496
  • 15
  • 91
  • 179
  • I'm quite positive this code can be greatly improved. I just went applying one hack after another *(based on SO research)* until it worked. – brasofilo Dec 30 '12 at 19:16
  • This works! This works with the code I used in my question, the 'Add-New-Default-Avatar' plugin, and also with an mu-plugin to change the default avatar. However, it breaks all other avatars built-in and test-user uploaded. But it works for development purposes! – gundam00 Dec 31 '12 at 08:51
  • @gundam00, for me the *user uploaded* avatars **do show**... [Useful Q&A's](http://wordpress.stackexchange.com/search?q=avatar_default). – brasofilo Dec 31 '12 at 13:23
  • since we're using the same code, for me, uploading an avatar thru the user's profile returns a blank box with the img src blank: However, the hacked custom avatar's img src shows the avatar's file location. But your hack allowed me to display the custom default avatar for testing purposes, which is what I needed. – gundam00 Jan 01 '13 at 01:55
  • To me the problem has been the option on the discussion settings of WordPress: the show avatar was unchecked! I was going to be crazy! – Mimo Jan 28 '13 at 07:18