I found a solution and now my frontend avatar script is fully functioning.
Happy days 🙂
I ended up scrapping the above code and using this.
add_filter( 'pre_get_avatar_data', 'wad_avatar_meta', 10, 2 );
function wad_avatar_meta( $args, $id_or_email ){
$user_avatar_meta_key = 'avatar';
if( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ){
$id_or_email = get_comment( $id_or_email );
}
if( $id_or_email instanceof WP_Post ){
$user_id = $id_or_email->post_author;
}
if( $id_or_email instanceof WP_Comment ){
if( ! empty( $id_or_email->user_id ) ){
$user_id = $id_or_email->user_id;
} elseif( ! empty( $id_or_email->comment_author_email ) ){
// If user_id not available, set as email address to handle below
$id_or_email = $id_or_email->comment_author_email;
}
}
if( is_numeric( $id_or_email ) ){
$user_id = $id_or_email;
} elseif( is_string( $id_or_email ) && strpos( $id_or_email, '@' ) ){
$id_or_email = get_user_by( 'email', $id_or_email );
}
if( $id_or_email instanceof WP_User ){
$user_id = $id_or_email->ID;
}
if( ! empty( $user_id ) && is_numeric( $user_id ) ){
$meta_val = maybe_unserialize( get_user_meta( $user_id, $user_avatar_meta_key, TRUE ) );
if( ! empty( $meta_val ) ){
if( is_array( $meta_val ) && ! empty( $meta_val[0] ) ){
$meta_val = $meta_val[0];
}
if( filter_var( $meta_val, FILTER_VALIDATE_URL ) ){
$args['url'] = $meta_val;
}
}
}
return $args;
}