phpwordpresswoocommercereview

Change review author name to first and last letters only with asterisks between in WooCommerce


I am using "How to Change the Review Author Display Name in WooCommerce" so that I can change the review author shown on the site to be the first name followed by surname initial.

add_filter('get_comment_author', 'my_comment_author', 10, 1);
function my_comment_author( $author = '' ) {
    // Get the comment ID from WP_Query
    $comment = get_comment( $comment_ID );
    if (!empty($comment->comment_author) ) {
        if($comment->user_id > 0){
            $user=get_userdata($comment->user_id);
            $author=$user->first_name.' '.substr($user->last_name,0,1).'.'; // this is the actual line you want to change
        } else {
            $author = __('Anonymous');
        }
    } else {
        $author = $comment->comment_author;
    }
    return $author;
}

What I need to do is to use the first name only (not show the surname) and change all but the first and last characters to '*'.

So for example James becomes J***s and Michael becomes M*****l


Solution

  • Adjustments are:

    comment added with explanation in the code

    function my_comment_author( $author, $comment_id, $comment ) {  
        // NOT empty
        if ( $comment ) {
            // Get user id
            $user_id = $comment->user_id;
    
            // User id exists
            if( $user_id > 0 ) {
                // Get user data
                $user = get_userdata( $user_id );
    
                // User first name
                $user_first_name = $user->first_name;
    
                // Call function
                $author = replace_with_stars( $user_first_name );       
            } else {
                $author = __('Anonymous', 'woocommerce');
            }
        }
    
        return $author;
    }
    add_filter('get_comment_author', 'my_comment_author', 10, 3 );
    
    function replace_with_stars( $str ) {
        // Returns the length of the given string.
        $len = strlen( $str );
    
        return substr( $str, 0, 1 ).str_repeat('*', $len - 2).substr( $str, $len - 1, 1 );
    }