将评论作者姓名更改为仅在 WooCommerce 中带有星号的第一个和最后一个字母

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

我正在使用“How to Change the Review Author Display Name in WooCommerce”,以便我可以将网站上显示的评论作者更改为名字后跟姓氏首字母。

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;
}

我需要做的是仅使用名字(不显示姓氏)并将除第一个和最后一个字符之外的所有字符更改为“*”。

例如,James 变成了 J***s,Michael 变成了 M*****l

调整为:

  • 显示名字
  • 詹姆斯成为J***s

在代码中添加了注释和解释

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 );
}