Change gravatar on product reviews from author email to comment email field using get_avatar wordpress hook

Enhancing user experience in your WordPress store is crucial for standing out and improving customer interaction and reviews area is one of the most used by customers who want to figure out if a certain product fits their needs or not, based on the experience of other users.

By default, WooCommerce products reviews use the avatar associated with the logged-in user, but it can be more beneficial to show the avatar based on the email provided in the comment. Here’s how you can achieve this.

What is Gravatar?

Gravatar (Globally Recognized Avatar) is a service that provides globally unique avatars based on users’ email addresses. When users comment on your site and provide their email, the corresponding Gravatar is displayed, adding a personal touch and increasing the authenticity of the reviews.

WordPress natively integrates Gravatar to grab comment/reviews profile image, as well as in other areas (such as back-end user pages).

Solution implementation

I struggle a little bit to find the right filter to use for my purpose; eventually I bumped into get_avatar.

This filter allows us to intercept and modify the displayed avatar based on the email entered in the comment field rather than the logged-in user e-email. Here’s the code to implement this solution:

<?php
function custom_get_avatar_for_product_review( $avatar, $id_or_email, $args ) {
    // Check if the object is a comment
    if ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) {
        $comment = $id_or_email;

        // Check if the comment is associated with a WooCommerce product
        if ( get_post_type( $comment->comment_post_ID ) == 'product' ) {
            // Get the commenter's email from the comment email field
            $commenter_email = get_comment_author_email( $comment->comment_ID );

            // Generate the Gravatar for the commenter's email
            $avatar = get_avatar( $commenter_email, $args['size'], $args['default'], $args['alt'], $args );
        }
    }

    return $avatar;
}
add_filter( 'get_avatar', 'custom_get_avatar_for_product_review', 10, 3 );

NOTE: As you can notice we limited this functionality to product post_type, you can change according to the needs you want to fullfill.

Hope this help people.