WordPress中对访客评论功能的一些优化方法(2)

>>> 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><span>欢迎回来, <strong>' . $comment_author . '</strong>.</span>'; $welcome_login .= ' <span><u>更改</u> <i></i></span></p>'; $comments_args['comment_field'] = '</div>' . $comments_args['comment_field']; $comments_args['comment_notes_before'] = $welcome_login . '<div>'; }

以上代码,需要添加到主题的 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('隐藏'); } }); });

这样,如果用户需要更新信息时,可以点击欢迎信息右侧的更改按钮;修改完成之后,用户信息会在评论后更新。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/92527721406332dbde9913557fa2e0bf.html