纯代码实现wp文章隐藏内容评论可见back

发布于 2021-02-21  1.3k 次阅读  共 1514 字


在社区论坛里,楼主发表帖子的时候一般会把重要内容隐藏起来,用户回复帖子后才能看见,有效地避免看帖不回,提高论坛的活跃度。把该功能引进wordpress网站,也能有效地提高网站的评论数量(当然垃圾评论也会相继增加),提高wordpress站点的活跃度。

在当前主题的functions.php文件添加以下代码:

//文章隐藏内容评论可见
function reply_to_read($atts, $content=null) {
        extract(shortcode_atts(array("notice" => '<p class="reply-to-read" style="border-width: 1px 1px 1px 1px;border-color: #F2F2F2;line-height: 150%;"><blockquote style="text-align: center;"><font color="#ff0000"><b>温馨提示</b></font>: 隐藏内容需要<a href="#respond" title="点击进行评论"> 回复评论 </a>后才能查看, 评论后请 <strong><a href="javascript:location.reload()" title="点击刷新"> 刷新 !</a></strong>.</blockquote></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 = "xxx@sey.ink"; //把左面的邮箱换成博主Email
            if ($email == $admin_email) {
                return $content;
            }
        } else if (isset($_COOKIE['comment_author_email_' . COOKIEHASH])) {
            $email = str_replace('%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');

注:把代码中的“xxx@sey.ink”换成博主邮箱地址

编辑文章的时候,使用[*reply][/reply*](没有*)把要评论可见的内容包围起来,如:

[*reply]评论可见的内容[/reply*] // 注:没有*

文章会显示:

温馨提示: 隐藏内容需要 回复/评论 后才能查看, 评论后请 刷新 !.

也可以使用格式:

[*reply notice="自定义的提示信息"] 评论可见的内容[/reply*] // 注:没有*

自定义温馨提示的内容。

提醒:如果开通了评论审核,那么内容需要评论审核通过后才可以看见!