·烂笔头Web端 25 4444

Typecho 给评论增加点赞/喜欢功能

之前换了主题以后,重新给文章增加了点赞功能。

那么又如何给每一条评论都增加点赞功能呢?参考了以下两篇文章后,重新做了调整。增加cookie,防止重复点赞。

目前该功能仅在【说说】界面。传送门:点击查看说说页面

参考文章1 参考文章2

修改function.php文件

找到themeInit函数,如没有,则自行编辑

function themeInit($self){
  //创建一个路由
    if ($self->request->getPathInfo() == "/getComment/dz") {
        //功能处理函数 - 评论点赞
        commentLikes($self);
    }
}

上下两种均可

function themeInit($archive){
  //创建一个路由
    if ($archive->request->getPathInfo() == "/getComment/dz") {
        //功能处理函数 - 评论点赞
        commentLikes($archive);
    }
}

增加方法函数1

/* 获取评论点赞数量 */
function commentLikesNum(<!--INLINEMATH0-->record = NULL)
{
    $db = Typecho_Db::get();
    $callback = array(
        'likes' => 0,
        'recording' => false
    );

    //  判断点赞数量字段是否存在
    if (array_key_exists('likes', <!--INLINEMATH1-->db->fetchRow(<!--INLINEMATH2-->coid)))) {
        //  查询出点赞数量
        <!--INLINEMATH3-->data['likes'];
    } else {
        //  在文章表中创建一个字段用来存储点赞数量
        <!--INLINEMATH4-->db->getPrefix() . 'comments` ADD `likes` INT(10) NOT NULL DEFAULT 0;');
    }

     //获取记录点赞的 Cookie
     //判断记录点赞的 Cookie 是否存在
    if (empty($recording = Typecho_Cookie::get('__typecho_comment_likes_record'))) {
        //  如果不存在就写入 Cookie
        Typecho_Cookie::set('__typecho_comment_likes_record', '[]');
    } else {
        <!--INLINEMATH5-->record = json_decode(<!--INLINEMATH6-->coid, $record);
    }

    //  返回
    return $callback;
}

增加方法函数2

/* 评论点赞处理 */
function commentLikes($archive)
{
    
    // 状态
    $archive->response->setStatus(200); 
    
    
    //评论id
    $_POST['coid'];
    
    /**
     * 行为
     * dz  进行点赞
     * ct  进行踩踏
    **/
    $_POST['behavior'];
    
    
    //判断是否为登录 true 为已经登录
    $loginState = Typecho_Widget::widget('Widget_User')->hasLogin();
    
    <!--INLINEMATH7-->_POST['coid'], $record);
    
    $num = 0;
    
    if(!empty(<!--INLINEMATH8-->_POST['behavior'])){
    
        $db = Typecho_Db::get();
        <!--INLINEMATH9-->db->getPrefix();
        <!--INLINEMATH10-->_POST['coid'];
        
        if (!array_key_exists('likes', <!--INLINEMATH11-->db->select()->from('table.comments')))) {
        <!--INLINEMATH12-->prefix . 'comments` ADD `likes` INT(30) DEFAULT 0;');
        }
        
        //先获取当前赞
        <!--INLINEMATH13-->db->fetchRow(<!--INLINEMATH14-->coid));
        
        <!--INLINEMATH15-->db->query(<!--INLINEMATH16-->row['likes'] + 1))->where('coid = ?', $coid));

    
        if($updateRows){
            <!--INLINEMATH17-->row['likes'] + 1;
            $state =  "success";
            
            //  添加点赞评论的 coid
            array_push(<!--INLINEMATH18-->coid);
            //  保存 Cookie
            Typecho_Cookie::set('__typecho_comment_likes_record', json_encode($record));
        }else{
            <!--INLINEMATH19-->row['likes'];
            $state =  "error";
        }
        
    }else{
        $state = 'Illegal request';
    }  

    //返回一个jsonv数据state数据
    $archive->response->throwJson(array(
       "state" => $state,
       "num" => $num
    ));    

}

编辑独立页面

HTML中需要增加点赞按钮的地方新增一下代码,样式自行编辑

<div class="right">
    <!-- 评论点赞次数 -->
    <?php 
        <!--INLINEMATH20-->comments->coid); 
        <!--INLINEMATH21-->commentLikes['likes'];
        <!--INLINEMATH22-->commentLikes['recording'];
    ?>
	<div class="commentLike">
	    <a class="commentLikeOpt" id="commentLikeOpt-<?php <!--INLINEMATH23-->comments->coid() ?>" data-recording="<?php echo $commentLikesRecording; ?>">
	    <i id="commentLikeI-<?php <!--INLINEMATH24-->commentLikesRecording?'st fa fa-heart':'st fa fa-heart-o'; ?>"></i
	    <span id="commentLikeSpan-<?php <!--INLINEMATH25-->commentLikesNum ?></span>
	    </a>
	</div>
</div>

HTML中增加js代码

<script>
    $("#comments-ajax").on('click', "a[id^='commentLikeOpt']", function() {
        
           var coid = $(this).data("coid");
           var recording = $(this).attr("data-recording");
           
           if(recording){
               alert("你已经点过赞啦!感谢你的喜爱!");
               return;
           }

            $.ajax({
                url: "<?php Helper::options()->index("/getComment/dz"); ?>",
                type: "POST",
                data: {
                    coid:coid,
                    behavior:'dz'
                },
                async: true,
                dataType: "json",
                success: function(data) {
                    if (data == null) {} else {
                        if(data.state == 'success'){
                            alert("点赞成功");
                            //修改点赞数量
                            $('#commentLikeSpan-'+coid).html(data.num);
                            //变更点赞图标样式
                            $('#commentLikeI-'+coid).removeAttr("class","st fa-regular fa-heart")
                            $('#commentLikeI-'+coid).attr("class","st fa-solid fa-heart")
                            //设置recording的属性值
                            $('#commentLikeI-'+coid).parent().attr("data-recording","1");
                        }
                        
                    }
                },
                error: function(err) {}
            });
            
        })
</script>

$("#comments-ajax") 代表整个评论区最外层的id是comments-ajax的标签,请自行修改。

例如<ol class="comment-list" id="comments-ajax">

特别注意

若出现点击“赞”无效;F12查看网络请求后,显示 Path ‘/getComment/dz’ not found 时

  1. JS代码中的url地址改为?commentLike
  2. themeInit 处改为:
if ($archive->request->is("commentLike")) {
  //功能处理函数 - 评论点赞
  commentLikes($archive);
}
13 个赞
本文最后更新于 2023年2月24日

评论 (25)

老何
老何
2024年9月30日 23:46 重庆市 移动 Windows
Call to undefined function   commentLikes() 大佬您好,点赞无效,显示如上错误,请问如何解决,不胜感激
Chrison
Chrison
2024年10月5日 20:18 无锡市 电信 Mac
提示没有commentLikes 方法啊,你加了吗
海角七号
海角七号
2023年2月24日 22:54 苏州市 电信 Mac
哇哦
荒野孤灯
荒野孤灯
2023年2月22日 21:01 黄石市 电信 Windows
我现在的代码邮件你了 现在是点赞没反应 忘了昨天怎么弄的!@##$
Chrison
Chrison
2023年2月22日 21:36 苏州市 电信 Mac
我是真想不通了。。。总不能是这个主题哪里有不兼容吧
荒野孤灯
荒野孤灯
2023年2月22日 22:09 武汉市 联通 Android
是不是跟文章的点赞冲突了
Chrison
Chrison
2023年2月23日 11:39 苏州市 电信 Mac
你是换了个邮箱吗,昨天都没注意有两个未审核的
Chrison
Chrison
2023年2月22日 21:36 苏州市 电信 Mac
但你昨天起码是好的
荒野孤灯
荒野孤灯
2023年2月22日 22:28 武汉市 联通 Android
现在不好了,忘了昨天咋弄的
Chrison
Chrison
2023年2月22日 23:28 苏州市 电信 Mac
解决了
Chrison
Chrison
2023年2月22日 23:30 苏州市 电信 Mac
独立页面的JS: 请求地址改成:`url: "?commentLike=dz",` fuction.php 的 themeInit 处改成: if ($archive->request->is("commentLike=dz")) { //功能处理函数 - 评论点赞 commentLikes($archive); }
Chrison
Chrison
2023年2月23日 00:57 苏州市 电信 Mac
`` Font Awesome 我们用的版本不一样。图标那一行,改成这个
海角七号
海角七号
2023年2月24日 22:58 苏州市 电信 Mac
1
荒野孤灯
荒野孤灯
2023年2月22日 20:12 黄石市 电信 Windows
if ($archive->request->getPathInfo() == "/getComment/dz") {
Chrison
Chrison
2023年2月22日 20:15 苏州市 电信 Mac
themeInit 这一段函数 都截图给我看看吧
荒野孤灯
荒野孤灯
2023年2月22日 20:17 黄石市 电信 Windows
https://s1.ax1x.com/2023/02/22/pSvau8O.png
Chrison
Chrison
2023年2月22日 20:20 苏州市 电信 Mac
???你改了 又好了?
荒野孤灯
荒野孤灯
2023年2月22日 20:22 黄石市 电信 Windows
没改啊 恢复 了 不正常啊 忘了昨天怎么搞的
Chrison
Chrison
2023年2月22日 20:23 苏州市 电信 Mac
你一部分 一部分的加,看看 还是说 一到themeInit那,就报错?
荒野孤灯
荒野孤灯
2023年2月22日 20:30 黄石市 电信 Windows
对啊 很奇怪
Chrison
Chrison
2023年2月22日 20:41 苏州市 电信 Mac
我改到仙人掌主题上,会找不到路由地址。、。。。。
荒野孤灯
荒野孤灯
2023年2月22日 20:48 黄石市 电信 Windows
Chrison
Chrison
2023年2月22日 20:54 苏州市 电信 Mac
或者你先按你昨天的方法弄,然后再修改
Chrison
Chrison
2023年2月22日 20:55 苏州市 电信 Mac
我也是见鬼了。 http://akina.chrison.cn/guests.html 这个主题上,死活找不到路由
荒野孤灯
荒野孤灯
2023年2月22日 20:10 黄石市 电信 Windows
帮忙看看

发表评论

支持 Markdown 语法