欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

WordPress 设置回复可见

IT技巧 迷途小书童 1年前 (2023-03-16) 502次浏览 0个评论

在使用 wordpress 主题时,有时候需要将部分内容隐藏,要求浏览者在评论中回复,然后显示隐藏的内容,以此来强化交互。

本篇使用插件的方法来实现,在 wordpress 安装目录下的 wp-content/plugin 新建一个文件夹,名称自取(比如 reply2view),然后进入文件夹,新建文件 index.php 并添加以下内容

<?php
/*
Plugin Name: Reply to View
Description: 将部分内容隐藏,回复可见。
Version: 1.0
*/

//部分内容评论可见,如果方法名和其它插件相同,可以重命名,该文件末尾还有一处
function reply_to_read($atts, $content = null, $admin_email = []) {
    extract(shortcode_atts(array("notice" => '<p class="reply-to-read">此处内容需要 <a href="#comments" 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 = "xxx@aaa.com";
        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');

然后,进入到 wordpress 后台,在插件里就能看到

wordpress reply to view

选中启用就 OK 了。

最后回到文件写作部分,在需要隐藏的内容的前后加上一对标签,如下

注意:本段内容须成功“回复本文”后“刷新本页”方可查看!

文章显示页面的效果是这样的

wordpress reply to view

喜欢 (0)

您必须 登录 才能发表评论!