Two things:
-
The
$id_or_email
can be an integer (a user ID), a string (Gravatar MD5 hash or user email) or an object (e.g. aWP_User
instance), so you can’t simply do$mail = $id_or_email->comment_author_email;
. -
The email addresses in your list are all in the form of
anonimus_<number>@anonimus.com
, so instead of defining that long array, you can simply use regular expression (RegEx).
(Update) Plus another thing:
-
Instead of the
get_avatar
filter/hook, you should probably just use thepre_get_avatar_data
hook since in yourmy_get_avatar()
function, you’re simply changing the avatar URL.That way (i.e. using the above hook), your callback would also work with
get_avatar_url()
and not justget_avatar()
.
So just remove the add_filter('get_avatar', 'my_get_avatar', 10, 5);
from your code (and remove also the my_get_avatar()
function), and then use the following instead:
add_filter( 'pre_get_avatar_data', 'my_pre_get_avatar_data', 10, 2 );
function my_pre_get_avatar_data( $args, $id_or_email ) {
// First, get the user's ID or email for unregistered comment authors.
if ( is_numeric( $id_or_email ) ) {
$user = get_user_by( 'id', $id_or_email );
} elseif ( $id_or_email instanceof WP_Comment ) {
$email = $id_or_email->comment_author_email;
$user = get_user_by( 'id', $id_or_email->user_id );
} elseif ( $id_or_email instanceof WP_Post ) {
$user = get_user_by( 'id', $id_or_email->post_author );
} elseif ( $id_or_email instanceof WP_User ) {
$user = get_user_by( 'id', $id_or_email->ID );
} else {
$user = get_user_by( 'email', $id_or_email );
}
// For registered users, get the email in the database.
if ( empty( $email ) && $user && ! is_wp_error( $user ) ) {
$email = $user->user_email;
}
// Then check the user's email and use the custom avatar, if applicable.
if ( ! empty( $email ) && preg_match( '/^anonimus_\d+@anonimus\.com$/', $email ) ) {
$args['url'] = 'http://example.com/wp-content/anonimus-avatar.png';
}
return $args;
}
But if you’d rather use the get_avatar
hook, then please let me know or just check this answer’s revisions.
In response to your comment:
please help to apply this to AMP pages too. filter
ampforwp_get_comments_gravatar
You should really ask in the plugin support forums, but let’s make an exception just this time, and you can try the following, which overrides the ampforwp_get_comments_gravatar()
function — yes, there’s a hook with the same name, but I don’t think it will work (because their code doesn’t pass the $comment
variable to the hook callbacks).
if ( ! function_exists( 'ampforwp_get_comments_gravatar' ) ) :
function ampforwp_get_comments_gravatar( $comment ) {
global $redux_builder_amp;
if ( ! empty( $redux_builder_amp['ampforwp-display-avatar'] ) ) {
return get_avatar( $comment );
}
return '';
}
endif;
That is untested, but it should work. And if you need further customization help, please, ask/post another question.