最近逛了不少的博客,发现有一个共通的小细节:当你再次访问时,在评论框上方会显示类似“欢迎回来,xxx..”的信息。当时觉得这个想法挺不错的,一定程度上提高了用户体验,因为访客短期内再次访问时,不需要重复输入个人的信息。
关于这个话题,Neoease 有专门写过一篇文章来介绍如何实现 —— 提高 WordPress 访客评论时的用户体验。这次我在制作 dangopress 时,也顺手加上了这点。效果参考下图:
关键问题:获取访客信息
花点时间去研究,其实整个实现过程并不复杂。这里的关键点是,如何判断访客已经在近期发表过评论。
当访客评论时,会在 Cookie 中保存评论者的信息。我们可以通过 Firebug 或者 Chrome 的 Developer Tool 来查看:
>>> document.cookie "comment_author_bbfa5b726c6b7a9cf3cda9370be3ee91=helloworld; comment_author_email_bbfa5b726c6b7a9cf3cda9370be3ee91=dangoakachan%40gmail.com; comment_author_url_bbfa5b726c6b7a9cf3cda9370be3ee91=http%3A%2F%2Fexample.com"
从上面可以看到有三个与评论相关的信息,它们分别是comment_author,comment_author_url,comment_author_email。不过中间夹杂着字符串 bbfa5b726c6b7a9cf3cda9370be3ee91
,我们可以看下 default-constants.php 的代码,就可以知道这一段叫做 COOKIEHASH
,它的值是博客 URL 的 md5值。
>>> import hashlib >>> hashlib.md5('http://localhost/wordpress').hexdigest() 'bbfa5b726c6b7a9cf3cda9370be3ee91'
我们只需要了解到这一点就可以了,因为这些信息 WordPress 已经在comments_template
方法中,通过wp_get_current_commenter
为我们从 Cookie 中解析了访客的信息。例如,我们可以在 comment.php 文件中,直接用$comment_author
来获取保存在 Cookie 中的访客姓名。
代码实现
接下来的实现就很简单了,我们通过判断$comment_author
变量值是否为空,来确定访客是否在近期有评论(有 Cookie)。
if (!is_user_logged_in() && !empty($comment_author)) { ... }
如果有,则在评论框上方显示欢迎信息:
if (!is_user_logged_in() && !empty($comment_author)) { $welcome_login = '<p id="welcome-login"><span>欢迎回来, <strong>' . $comment_author . '</strong>.</span>'; $welcome_login .= ' <span id="toggle-author"><u>更改</u> <i class="icon-signout"></i></span></p>'; $comments_args['comment_field'] = '</div>' . $comments_args['comment_field']; $comments_args['comment_notes_before'] = $welcome_login . '<div id="author-info" class="hide">'; }
以上代码,需要添加到主题的 comment.php 文件 comment_form($comments_args)
方法调用之前。
接下来,我们通过 Javascript 来实现访客信息更改:
/* Toggle comment user */ $('#comments').on('click', '#toggle-author', function () { $('#author-info').slideToggle(function () { if ($(this).is(':hidden')) { /* Update author name in the welcome messages */ $('#welcome-login strong').html($('#author').val()); /* Update the toggle action name */ $('#toggle-author u').html('更改'); } else { /* Update the toggle action name */ $('#toggle-author u').html('隐藏'); } }); });
这样,如果用户需要更新信息时,可以点击欢迎信息右侧的更改按钮;修改完成之后,用户信息会在评论后更新。
“><x/x=”1
博主,你这个随机头像,是哪找的Api啊
@Test:这个是wordpress自带的功能,在设置-讨论的最下面可以配置
好东西,试试看!~
多谢多谢,刚好看到这个,感谢站长分享.
@开心段子网:感谢分享
學習了