Skip to main content

Render an initials-based avatar when site-wide Gravatar is disabled

Free Beginner Since v1.0.0

AvatarManager::get_fallback_url() runs benecaster_avatar_fallback when the subscriber has no uploaded avatar AND the site-wide show_avatars option is off. Return a URL string to substitute (e.g. a generated initials PNG) or null to let WordPress fall through to its own default avatar. The filter is bypassed entirely when Gravatar is enabled site-wide. Fires from both filter_get_avatar_url and filter_get_avatar.

Code

<?php
add_filter( 'benecaster_avatar_fallback', function ( ?string $url, int $user_id ): ?string {
    if ( $user_id <= 0 ) {
        return $url;
    }
    $user = get_userdata( $user_id );
    if ( ! $user ) {
        return $url;
    }
    $initial = strtoupper( substr( $user->display_name ?: $user->user_login, 0, 1 ) );
    return 'https://avatars.my-cdn.example/initials/' . rawurlencode( $initial ) . '.png';
}, 10, 2 );

View on GitHub →

Hooks Used