转载地址:WordPress 评论解锁插件开发教程
一个优秀的网站不仅要有高质量的内容,还要有巧妙的互动机制。比如一些干货内容,只向用心评论者开放。
现在,我们就一起来探讨一个实现“评论后解锁可见内容”的WordPress 插件。
* * *
该插件的核心功能包括:
完整代码如下:
核心文件:reply-display/reply-display.php
<?php
/*
Plugin Name: reply-display
Plugin URI: https://www.woolyun.com
Description: 让文章中的部分内容只有评论后才可见
Version: 1.1
Author: ctihai
*/
date_default_timezone_set('Asia/Shanghai');
// 当评论插入时设置特定文章ID的Cookie
add_action('wp_insert_comment', 'set_comment_postid', 10, 2);
function set_comment_postid($comment_id, $comment) {
if ($comment->comment_approved == 1) { // 仅当评论已审核时设置
$post_id = $comment->comment_post_ID;
setcookie("reply_$post_id", "1", time() + 3600 * 24 * 30, "/");
}
}
// 添加短代码 [replydis]...[/replydis]
add_shortcode('replydis', 'reply_read_shortcode');
function reply_read_shortcode($atts, $content = null) {
$post_id = get_the_ID();
// 如果用户已经评论过本文,返回内容
if (has_replied($post_id)) {
return do_shortcode($content);
}
// 默认返回提示语句
$atts = shortcode_atts([
'notice' => '<div class="replydis"><p>温馨提示:此处内容需要<a href="#respond" title="评论本文">评论本文</a>后才能查看。</p></div>'
], $atts);
return $atts['notice'];
}
// 判断用户是否评论过本文
function has_replied($post_id) {
global $wpdb;
//检查 Cookie
$cookie_name = "reply_$post_id";
return isset($_COOKIE[$cookie_name]) && $_COOKIE[$cookie_name] === '1';
}
// 加载CSS样式
function reply_read_enqueue_style() {
wp_enqueue_style('reply-to-style', plugins_url('css/replydis.css', __FILE__));
}
add_action('wp_enqueue_scripts', 'reply_read_enqueue_style');css文件:reply-display/css/replydis.css
.replydis{
background: #CCCCCC;
color: #000000;
font-family: "Microsoft YaHei","微软雅黑","幼圆","宋体","楷体","楷体_GB2312";
font-size: 16px;
font-weight:bold;
font-style: normal;
margin:0;
padding: 10px 20px;
line-height: normal;
}这些功能由几个关键函数组成,下面我们逐个解析它们的用途和意义。
* * *
set_comment_postid()当用户提交评论时,这个函数被触发,并设置一个带文章 ID 的 Cookie,例如:reply_123=1,其中 123 是文章的 ID。
📌 作用:
* * *
reply_read_shortcode()这是短代码 [replydis]...[/replydis] 的处理函数。它决定了内容是否展示给用户。
📌 作用:
📌 特点:
* * *
has_replied()该函数负责最终判断用户是否真正“评论过”当前文章。
📌 作用:
📌 妙处:
* * *
reply_read_enqueue_style()用于加载 CSS 文件,使插件样式美观统一。
📌 作用:
replydis.css* * *
功能 | 描述 |
|---|---|
精确识别文章ID | 用户评论哪篇,解锁哪篇 |
游客友好体验 | 用 Cookie 实现便捷解锁 |
样式可定制 | 支持 CSS 调整外观 |
我们不要简单地复制粘贴,而是要深思熟虑地重构每一步逻辑。
* * *
“知之愈明,则行之愈笃。”
通过这篇文章,你已经了解了如何构建一个“评论可见”插件的核心逻辑。
请记住:好的插件,始于一行代码,终于用户的体验。

本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。