WooCommerce评论作者名修改:仅显示名字首尾字母,中间替换为星号
Got it, let's tweak your existing code to make the comment author show only the first name with all middle characters replaced by asterisks (like James → Js, Michael → M**l). Here's the updated, tested solution:
add_filter('get_comment_author', 'my_comment_author', 10, 1); function my_comment_author( $author = '' ) { // Get the current comment object $comment = get_comment(); if (!empty($comment->comment_author) ) { if($comment->user_id > 0){ $user = get_userdata($comment->user_id); $first_name = $user->first_name; // Handle the name masking logic if (strlen($first_name) <= 2) { // If name is 2 characters or shorter, show as-is (e.g. "Al" stays "Al") $author = $first_name; } else { // Take first character, add asterisks for middle, then last character $first_char = substr($first_name, 0, 1); $last_char = substr($first_name, -1); $middle_asterisks = str_repeat('*', strlen($first_name) - 2); $author = $first_char . $middle_asterisks . $last_char; } } else { $author = __('Anonymous'); } } else { $author = $comment->comment_author; } return $author; }
Key changes explained:
- Removed the last name handling entirely since we only need the first name now.
- Added a conditional to handle short names (2 characters or less) so we don't end up with odd outputs like "J*s" for a 2-letter name.
- Used
str_repeat('*', strlen($first_name) - 2)to dynamically generate the correct number of asterisks based on the name length—this works seamlessly for any first name length, from 3 characters upward.
How to implement:
Add this code to your active theme's functions.php file, or use a custom code snippets plugin to avoid losing changes when you update your theme.
内容的提问来源于stack exchange,提问作者Lyall
相关产品推荐
相关产品推荐

