首先找到functions.php
,加入以下函数
function agreeNum($cid, &$record = NULL){ $db = Typecho_Db::get(); $callback = array( 'agree' => 0, 'recording' => false ); // 判断点赞数量字段是否存在 if (array_key_exists('agree', $data = $db->fetchRow($db->select()->from('table.contents')->where('cid = ?', $cid)))) { // 查询出点赞数量 $callback['agree'] = $data['agree']; } else { // 在文章表中创建一个字段用来存储点赞数量 $db->query('ALTER TABLE `' . $db->getPrefix() . 'contents` ADD `agree` INT(10) NOT NULL DEFAULT 0;'); } // 获取记录点赞的 Cookie // 判断记录点赞的 Cookie 是否存在 if (empty($recording = Typecho_Cookie::get('__typecho_agree_record'))) { // 如果不存在就写入 Cookie Typecho_Cookie::set('__typecho_agree_record', '[]'); } else { $callback['recording'] = is_array($record = json_decode($recording)) && in_array($cid, $record); } // 返回 return $callback;}function agree($cid){ $db = Typecho_Db::get(); $callback = agreeNum($cid, $record); // 获取点赞记录的 Cookie // 判断 Cookie 是否存在 if (empty($record)) { // 如果 cookie 不存在就创建 cookie Typecho_Cookie::set('__typecho_agree_record', "[$cid]"); } else { // 判断文章是否点赞过 if ($callback['recording']) { // 如果当前文章的 cid 在 cookie 中就返回文章的赞数,不再往下执行 return $callback['agree']; } // 添加点赞文章的 cid array_push($record, $cid); // 保存 Cookie Typecho_Cookie::set('__typecho_agree_record', json_encode($record)); } // 更新点赞字段,让点赞字段 +1 $db->query('UPDATE `' . $db->getPrefix() . 'contents` SET `agree` = `agree` + 1 WHERE `cid` = ' . $cid . ';'); // 返回点赞数量 return ++$callback['agree'];}
然后找到post.php
在顶部加入以下代码用于判断是否是点赞的 POST 请求:
if (isset($_POST['agree'])) { // 判断 POST 请求中的 cid 是否是本篇文章的 cid if ($_POST['agree'] == $this->cid) { // 调用点赞函数,传入文章的 cid,然后通过 exit 输出点赞数量 exit( strval(agree($this->cid)) ); } // 如果点赞的文章 cid 不是本篇文章的 cid 就输出 error 不再往下执行 exit('error');}
接下来在该页面加入点赞按钮(按钮样式自行修改):
<?php $agree = $this->hidden?array('agree' => 0, 'recording' => true):agreeNum($this->cid); ?> <button <?php echo $agree['recording']?'disabled':''; ?> type="button" id="agree" data-cid="<?php echo $this->cid; ?>" data-url="<?php $this->permalink(); ?>" class="btn btn-w-md btn-round btn-secondary"> <span>点赞</span> <span class="agree-num"><?php echo $agree['agree']; ?></span>//点赞数量 </button>
最后Ajax点赞:
以下js代码添加至footer.php
中,
// 点赞按钮点击 $('#agree').on('click', function () { // 发送 AJAX 请求 $.ajax({ // 请求方式 post type: 'post', // url 获取点赞按钮的自定义 url 属性 url: $('#agree').attr('data-url'), // 发送的数据 cid,直接获取点赞按钮的 cid 属性 data: 'agree=' + $('#agree').attr('data-cid'), async: true, timeout: 30000, cache: false, // 请求成功的函数 success: function (data) { var re = /\d/; // 匹配数字的正则表达式 // 匹配数字 if (re.test(data)) { // 把点赞按钮中的点赞数量设置为传回的点赞数量 $('#agree .agree-num').html(data); } //这里可以添加点赞成功后的效果代码,根据自身需求添加 $('#agree').get(0).disabled = true; // 禁用点赞按钮 }, error: function () { // 如果请求出错就恢复点赞按钮 $('#agree').get(0).disabled = false; }, }); });