我试图将评论作者的名字(或者更具体地说,WooCommerce中的评论作者)改为名字的首字母(例如,“John D.”代表“John Doe”)。
我通过以下函数中的代码获得了大部分方法。php,但出于某种原因(可能是因为评论/评论是如何提交的),它倾向于将名称留空,并用句号(“.”)替换在一些(并非全部)评论中。
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 (!empty($comment->user_id)){
$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 {
$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
}
return $author;
}
但是,如果我将代码这样调整为回退,它总是显示全名: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 (!empty($comment->user_id)){
$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;
}
我希望数据库中的实际名称保持不变,只需过滤网站面向公众一侧的输出以获取评论(我们可能需要在其他地方显示他们的全名,但在评论作者正确显示之前无法真正测试)。