博客 / WordPress/ WordPress部分文章内容评论/回复后可见

WordPress部分文章内容评论/回复后可见

WordPress部分文章内容评论/回复后可见

如果我们希望隐藏文章部分内容,需要用户评论可见、回复可见,那么今天这篇WordPress教程文章就刚好适合你。

这个功能实现起来很容易,而且可以提高用户积极性,是一个非常不错的功能。

下面是实现此功能的核心代码。

// WordPress实现文章部分内容评论后可见
function reply_to_read($atts, $content=null) {
    extract(shortcode_atts(array("notice" => '<p class="reply-to-read">温馨提示: 此处内容需要<a href="#respond" rel="external nofollow" title="评论本文">评论本文</a>后才能查看.</p>'), $atts));
    $email = null;
    $user_ID = (int) wp_get_current_user()->ID;
    if ($user_ID > 0) {
        $email = get_userdata($user_ID)->user_email;
        // 对博主直接显示内容
        $admin_email = "leixue@leiue.com"; // 博主 Email,请修改为你的邮箱
        if ($email == $admin_email) {
            return $content;
        }
    } else if (isset($_COOKIE['comment_author_email_' . COOKIEHASH])) {
        $email = str_replace('{5cc1b29162d549a8071384de182cc9fc6e6a0fd85e7907f22fd9e18cff4269c3}40', '@', $_COOKIE['comment_author_email_' . COOKIEHASH]);
    } else {
        return $notice;
    }
    if (empty($email)) {
        return $notice;
    }
    global $wpdb;
    $post_id = get_the_ID();
    $query = "SELECT `comment_ID` FROM {$wpdb->comments} WHERE `comment_post_ID`={$post_id} and `comment_approved`='1' and `comment_author_email`='{$email}' LIMIT 1";
    if ($wpdb->get_results($query)) {
        return do_shortcode($content);
    } else {
        return $notice;
    }
}
add_shortcode('reply', 'reply_to_read');

使用方法

1. 将上述代码添加到当前主题的 functions.php 文件末尾。

2. 在编辑文章时,使用短代码 [reply] 包裹需要隐藏的内容。例如:

[reply]这是需要评论后才能查看的隐藏内容。[/reply]

最终效果如下:

温馨提示: 此处内容需要评论本文后才能查看。

(用户评论后,此处将显示“这是需要评论后才能查看的隐藏内容。”)

代码说明与注意事项

  • 博主邮箱:代码中的 $admin_email = "leixue@leiue.com"; 需要修改为你自己的邮箱地址,以确保博主登录后可以直接看到隐藏内容。
  • 短代码名称:代码注册的短代码是 [reply],你也可以在 add_shortcode('reply', 'reply_to_read'); 这行中修改第一个参数来改变短代码名称。
  • 安全性:此代码通过检查用户邮箱是否存在于已批准的评论中来判断权限,是一种常见方法。请注意,如果网站允许游客评论,此功能才对他们有效。
  • 缓存兼容性:如果网站使用了静态缓存或对象缓存,此动态判断功能可能会受到影响,需要考虑缓存插件的排除规则。

1 条评论

  1. 我试试

回复 lee 取消回复

您的邮箱不会公开。必填项已用 * 标注。