EN / ZH
Adding a "Comment to Reveal" Shortcode to WordPress

If you frequent forums, you’ve probably encountered posts where certain content is only visible after you reply. I think this feature is quite useful — it boosts comment counts and helps prevent content from being scraped by bots.

This handy feature can now be implemented in WordPress as well. I copied the code directly from Lao Yang’s blog. I’ve seen about three versions of this code floating around, and I picked the relatively concise one. If your blog frequently shares download links and you’d rather visitors leave a comment instead of just grabbing the download, then read on…

First, add the following code to your theme’s functions.php

< ?php
/**
* Shortcode: Comment to Reveal
* @xiaowu Zhouliang's Blog (https://imzl.com)
*/
function reply_to_read($atts, $content = null) {
    extract(shortcode_atts(array("notice" = >'<p class="reply-to-read">Note: This content requires you to <a href="#respond" title="Comment on this post">leave a comment</a> before viewing.</p>'), $atts));
    $email = null;
    $user_ID = (int) wp_get_current_user() - >ID;
    if ($user_ID > 0) {
        $email = get_userdata($user_ID) - >user_email;
        //Show content directly for the site admin
        $admin_email = "xxx@aaa.com"; //Admin email address
        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'); ? >

Then use the shortcode in your posts:

[reply]Hidden content here[/reply]

You can also customize the notice message:

[reply notice="Custom notice message"]Content revealed after commenting[/reply]
PS: With the code I’ve provided, the site admin can see the hidden content without needing to comment!

There you go — the comment-to-reveal shortcode is ready. Why not give it a try?