WordPress隐藏部分内容,评论后可见

教程介绍

通过本文章的代码可以实现隐藏WordPress部分内容,让用户评论可见,如果你设置, 登陆用户才可以评论,还可以达到用户登陆后评论可见的效果。

将下面的代码添加到主题的 functions.php 文件:

  1. //部分内容评论可见
  2. function reply_to_read($atts, $content=null) {   
  3.         extract(shortcode_atts(array("notice" => '<p class="reply-to-read">温馨提示: 此处内容需要<a href="#respond" title="评论本文">评论本文</a>后才能查看.</p>'), $atts));   
  4.         $email = null;   
  5.         $user_ID = (int) wp_get_current_user()->ID;   
  6.         if ($user_ID > 0) {   
  7.             $email = get_userdata($user_ID)->user_email;   
  8.             //对站长直接显示内容   
  9.             $admin_email = "admin@ymjihe.com"; //站长Email   
  10.             if ($email == $admin_email) {   
  11.                 return $content;   
  12.             }   
  13.         } else if (isset($_COOKIE['comment_author_email_' . COOKIEHASH])) {   
  14.             $email = str_replace('%40', '@', $_COOKIE['comment_author_email_' . COOKIEHASH]);   
  15.         } else {   
  16.             return $notice;   
  17.         }   
  18.         if (empty($email)) {   
  19.             return $notice;   
  20.         }   
  21.         global $wpdb;   
  22.         $post_id = get_the_ID();   
  23.         $query = "SELECT `comment_ID` FROM {$wpdb->comments} WHERE `comment_post_ID`={$post_id} and `comment_approved`='1' and `comment_author_email`='{$email}' LIMIT 1";   
  24.         if ($wpdb->get_results($query)) {   
  25.             return do_shortcode($content);   
  26.         } else {   
  27.             return $notice;   
  28.         }   
  29.     }   
  30.  
  31.     add_shortcode('reply', 'reply_to_read');

注:请自行修改第8行的邮件为管理员的。如果你的网站使用了ajax免刷新提交评论,你可能需要修改第2行的提示文字,提示访客评论后刷新页面来查看隐藏内容。

调用方法

编辑文章时,使用下面的两种简码调用:

  1. //简码1  任选一种使用
    
  2. [reply]评论可见的内容[/reply]
    
  3. //简码2  任选一种使用
    
  4. [reply notice="自定义的提示信息"]评论可见的内容[/reply]

评论9

评论前必须登录!

  1. #0
    网页显示中文字乱码了
    ddd2019-01-13 17:01:28
  2. #0
    可惜我怎么弄都不成功
    荣耀博客2018-06-24 13:51:19
  3. #0
    不错的文章!