开发者

Display username to logged in user only?

I have a Wordpress blog set up to display comments as "Anonymous User" by hard coding it into the comments.php file. I would like to have it say the user's Username next to their comment and ONLY display that Username to THEM. In other words, if they're a guest, they'll see "Anonymous User" and if they're a registered/logged in DIFFERENT user, they'll still see "Anonymous Us开发者_StackOverflow社区er", but if it's THEIR comment it'll say "Your Comment" or their own username. Any clue on a snippet of code? Here's what I have so far:

Anonymous User: <div class="post-txt" id="<?php comment_ID() ?>"><?php comment_text() ?></div>

Thanks!


function my_custom_comment_author_filter($author){
  global $current_user;
  wp_get_current_user();
  if(!is_category(3)){
    return $author;
  }
  if(0 == $current_user->ID || ($current_user->display_name !== $author && $current_user->user_login !== $author)){
    return 'Anonymous User';
  }
  return $author;
}

add_filter('get_comment_author', 'my_custom_comment_author_filter');


Basically, you will need to get the comment author's ID, get the logged in user's ID and compare the two. Have a look at getting the current logged in user and getting information about the current comment from the Codex.

I haven't tested this snippet, but it should point you in the right direction:

<?php global $user_id, $user_login; 
    get_currentuserinfo();  // This will populate $user_id with the logged in user's ID or '' if not logged in
    $the_comment = get_comment(comment_ID());  // Get a comment Object...
    $author_id = $the_comment->user_id; // and extract the commenter's ID

    if($user_id !== '' && $author_id == $user_id){
        echo 'Your comment [ ' . $user_login . ' ]:';
    }
    else{
        echo 'Anonymous User:';
    }
?>


Check if the current visitor is logged in http://codex.wordpress.org/Function_Reference/is_user_logged_in

<?php if ( is_user_logged_in() ) { 
    ....
} else {
    ....
} ?> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜