I am trying to edit the avatar that is called from Woocommerce’s review tab in a product page. This is my piece of code that works but it also manipulates the admin menubar, which is something I do not want it to do.
I am using this hook to apply the initials of the reviewer, instead of their Gravatar image.
// Apply filter
add_filter( 'get_avatar' , 'my_custom_avatar' , 1 , 5 );
function my_custom_avatar( $avatar, $id_or_email, $size, $default, $alt ) {
$user = false;
if ( !is_product() ) return $avatar;
if ( is_numeric( $id_or_email ) ) {
$id = (int) $id_or_email;
$user = get_user_by( 'id' , $id );
} elseif ( is_object( $id_or_email ) ) {
if ( ! empty( $id_or_email->user_id ) ) {
$id = (int) $id_or_email->user_id;
$user = get_user_by( 'id' , $id );
}
} else {
$user = get_user_by( 'email', $id_or_email );
}
if ( $user && is_object( $user ) ) {
$user_name = explode(" ", $user->display_name);
$avatar = '<div class="cnc_customer-review-profile">
<span>' . substr($user_name[0], 0, 1) . substr($user_name[1], 0, 1) . '</span>
</div>';
}
return $avatar;
}
Is there a way to apply a filter to a specific part of a page?
I have added the check to confirm if we are on a product page and within the WooCommerce review section and update the code accordingly.
add_filter( 'get_avatar' , 'my_custom_avatar', 10, 5 );
function my_custom_avatar( $avatar, $id_or_email, $size, $default, $alt ) {
// Here we are checking if we are on a product page and within the WooCommerce review section.
if ( ! is_product() || ! did_action( 'woocommerce_review_before_comment_text' ) ) {
return $avatar;
}
$user = false;
if ( is_numeric( $id_or_email ) ) {
$id = (int) $id_or_email;
$user = get_user_by( 'id' , $id );
} elseif ( is_object( $id_or_email ) ) {
if ( ! empty( $id_or_email->user_id ) ) {
$id = (int) $id_or_email->user_id;
$user = get_user_by( 'id' , $id );
}
} else {
$user = get_user_by( 'email', $id_or_email );
}
if ( $user && is_object( $user ) ) {
$user_name = explode(' ', $user->display_name);
$initials = isset( $user_name[1] ) ? substr( $user_name[0], 0, 1 ) . substr( $user_name[1], 0, 1 ) : substr( $user_name[0], 0, 1 );
$avatar = '<div class="cnc_customer-review-profile">
<span>' . $initials . '</span>
</div>';
}
return $avatar;
}
This should works for you.
1