功能简介
文章点赞功能在单篇文章末尾提供一个「点赞」按钮,访客(无需登录)点击后即可记录一次点赞,按钮实时显示累计点赞数,提升互动与内容热度感知。
如何开启
进入 WordPress 后台 → 「Vela主题设置」页面的「功能开关」分区 → 找到「文章点赞」→ 勾选启用并保存。
效果与适用场景
- 无需登录即可点赞,同一访客按会话去重。
- 点赞数保存在文章自定义字段中,安全持久。
- 适合社区、博客类站点增强互动。
备注
仅在前台单篇文章页显示;关闭开关后不再渲染点赞按钮。
实现代码
以下为「文章点赞」的核心实现(取自 modules/like.php、features.js 与 features.css)。
<?php
/**
* 文章点赞模块(modules/like.php)
* 在单篇文章末尾追加点赞按钮(无需登录),点赞数保存于文章自定义字段,
* 同一访客按会话 Cookie 去重。
*/
add_filter('the_content', 'vela_like_button_append');
function vela_like_button_append($content) {
if (!vela_feature_enabled('like')) {
return $content;
}
if (!is_singular('post')) {
return $content;
}
$post_id = get_the_ID();
$count = (int) get_post_meta($post_id, '_vela_like_count', true);
$btn = '<button type="button" class="vela-like-btn" data-post-id="' . esc_attr($post_id) . '">';
$btn .= '点赞 <span class="vela-like-count">' . esc_html($count) . '</span>';
$btn .= '</button>';
return $content . $btn;
}
// AJAX 处理(登录 / 未登录均可)
function vela_like_ajax() {
check_ajax_referer('vela_like', 'nonce');
$post_id = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0;
if (!$post_id) {
wp_send_json_error('invalid');
}
$key = 'vela_liked_' . $post_id;
$count = (int) get_post_meta($post_id, '_vela_like_count', true);
if (empty($_COOKIE[$key])) {
$count++;
update_post_meta($post_id, '_vela_like_count', $count);
setcookie($key, '1', 0, '/');
}
wp_send_json_success(array('count' => $count));
}
add_action('wp_ajax_nopriv_vela_like', 'vela_like_ajax');
add_action('wp_ajax_vela_like', 'vela_like_ajax');
/* ---------- 文章点赞(features.js 片段) ---------- */
if (C.like) {
$all('.vela-like-btn').forEach(function (b) {
b.addEventListener('click', function () {
if (b.classList.contains('liked')) { return; }
var pid = b.getAttribute('data-post-id');
b.disabled = true;
var xhr = new XMLHttpRequest();
xhr.open('POST', C.ajaxurl, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
try {
var r = JSON.parse(xhr.responseText);
if (r && r.success) {
var c = b.querySelector('.vela-like-count');
if (c) { c.textContent = r.count; }
b.classList.add('liked');
}
} catch (err) { /* ignore */ }
b.disabled = false;
};
xhr.send('action=vela_like&post_id=' + encodeURIComponent(pid) + '&nonce=' + encodeURIComponent(C.like_nonce));
});
});
}
/* 文章点赞按钮(features.css 片段) */
.vela-like-btn {
display: inline-flex;
align-items: center;
gap: 8px;
margin: 26px 0 6px;
padding: 9px 20px;
border: 1px solid #2f6fed;
color: #2f6fed;
background: #fff;
border-radius: 999px;
cursor: pointer;
font-size: 14px;
transition: all .2s ease;
}
.vela-like-btn:hover { background: #f0f5ff; }
.vela-like-btn.liked { background: #2f6fed; color: #fff; }
.vela-like-btn .vela-like-count { font-weight: 600; }
前端所需的 ajaxurl 与 like_nonce 同样由 loader.php 注入:$config['ajaxurl'] = admin_url('admin-ajax.php');$config['like_nonce'] = wp_create_nonce('vela_like');
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END


暂无评论内容