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


当前第2页 返回上一页

关键问题:获取访客信息

花点时间去研究,其实整个实现过程并不复杂。这里的关键点是,如何判断访客已经在近期发表过评论。

当访客评论时,会在 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('隐藏');
    }  
  }); 
}); 

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


标签:WordPress

返回前面的内容

相关阅读 >>

wordpress评论添加楼层显示的方法小结

wordpress用户登录框密码的隐藏与部分显示技巧

升级nginx支持http2服务端推送的方法

快速建立个人网站知识 域名+网络空间+站点平台

在centos 6 中安装wordpress(一) 安装apache,mysql, php环境

wordpress分类目录、标签丢失问题的解决方法

wordpress实现的首页幻灯片展示功能示例【附demo源码】

#实践笔记#本地配置phpnow与wordpress运行环境

linux nginx下ssl证书安装方法及wordpress cdn配置

wordpress提示require_once() failed opening required的解决方法

更多相关阅读请进入《wordpress》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...