查看: 198|回复: 0

[技术教程] Typecho通过Cookie实现游客评论记录功能

[复制链接]
  • 打卡等级:常驻代表
  • 打卡总天数:49
  • 打卡月天数:0
  • 打卡总奖励:383
  • 最近打卡:2025-08-20 09:34:54
发表于 2025-8-20 13:50:51 | 显示全部楼层 |阅读模式
cookieyouke.png

注意以下第一步和第二步代码可以放到functions.php这个文件中(注意:最好放到文件末尾避免)

第一步添加浏览记录代码
  1. <?php
  2. class xm{

  3.         public static function logComment($comment, $post){

  4.         $cookie = Typecho_Cookie::get('__comment_history');
  5.         $history = $cookie ? json_decode($cookie, true) : array();
  6.         
  7.         // 添加到数组开头
  8.         array_unshift($history, array(
  9.             'cid' => $comment['cid'],
  10.             'coid' => $comment['coid'],
  11.             'text' => $comment['text'],
  12.             'created' => $comment['created'],
  13.             'author' => $comment['author'],
  14.             'status' => $comment['status']
  15.         ));
  16.         
  17.         // 限制最多保存5条记录
  18.         $history = array_slice($history, 0, 5);
  19.         
  20.         Typecho_Cookie::set('__comment_history', json_encode($history), time() + 3600 * 24 * 30);
  21.         
  22.         return $comment;
  23.     }
  24. }
复制代码
第二步添加详情页面插件钩子挂载点(array('xm', 'addHistory')通过这个数组传递上面第一步定义的类,xm是上面类的名称,addHistory是上面类中的方法)
  1. Typecho_Plugin::factory('Widget_Feedback')->comment = array('xm', 'logComment');
复制代码
第三步,就是在你需要显示的地方调用下面代码。(其中的样式根据自己主题风格自行修改)
  1. <?php
  2.           $comment = Typecho_Cookie::get('__comment_history');
  3.           $comment = $comment ? json_decode($comment, true) : array();
  4.           if ($comment) {
  5.           ?>
  6.           <div class="xm-zuji">
  7.             <?php foreach ($comment as $item) {
  8.               echo '<div class="xm-zuji-div"><span class="xm-zuji-time xm-txt-ellipsis">'.$item['author'].'</span><span class="xm-zuji-a xm-txt-ellipsis">'.xm::time($item['created']).'评论了:'.xm::biaoqing($item['text']).'</span></div>';
  9.             }
  10.             ?>
  11.           </div>
  12.         <?php }else{echo '<div class="xm-zuji-xx">暂无过往的评论消息</div>';} ?>
复制代码
原文地址
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表