本页目录

通过本文章的代码可以实现隐藏 WordPress 部分内容,让用户评论可见,如果你设置, 登陆用户才可以评论,还可以达到用户登陆后评论可见的效果。这一节的 WordPress 开发教大家如何实现上述功能。
- 代码来源:详情

将下面的代码添加到主题根目录下的 functions.php 文件的<?php>下面:
//部分内容评论可见function reply_to_read($atts, $content=null) { extract(shortcode_atts(array("notice" => '<p class="reply-to-read">温馨提示: 此处内容需要<a href="#respond" 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 = "admin@ymjihe.com"; //站长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');注:请自行修改第 8 行的邮件为管理员的。如果你的网站使用了 ajax 免刷新提交评论,你可能需要修改第 2 行的提示文字,提示访客评论后刷新页面来查看隐藏内容。
调用方法
编辑文章时,使用下面的两种简码调用:
//简码1 任选一种使用
[reply]评论可见的内容[/reply]
//简码2 任选一种使用
[reply notice="自定义的提示信息"]评论可见的内容[/reply]下面这段,是另外一个代码,但我不知道怎么使用,懂代码的同学请在评论区留言
function iepress_commentonly_shortcode( $atts, $content ){ // set some default values $display_message = __( 'You Must be Logged in and Commented to view this content,', 'iepress' ); $logined_message = __( 'You Must be Commented to view this content,', 'iepress' ); $link = wp_login_url( get_permalink() ); $linktext = __( 'Register or Login Here', 'iepress' ); $commenttext = __( 'Comment Here', 'iepress' );
$atts = shortcode_atts( array( 'display' => $display_message, 'logined'=> $logined_message, 'linkto' => $link, 'linktext' => $linktext, 'commenttext' =>$commenttext, ), $atts );
if( !is_null( $content ) ) : if(!is_user_logged_in()){ $content = '' . $atts['display'] . '<a class="wpu-login-btn" href=" '. $atts['linkto'] . ' " title="'. $atts['linktext'] . '">'. $atts['linktext'] . '</a>';
}else{ global $post; $user_id = get_current_user_ID(); if( $user_id != $post->post_author && !user_can($user_id,'edit_others_posts') ){ $comments = get_comments( array('status' => 'approve', 'user_id' => get_current_user_ID(), 'post_id' => $post->ID, 'count' => true ) ); if(!$comments) { $content = '' . $atts['logined'] . '<a class="wpu-login-btn" href=" '.get_comments_link().' " title="'. $atts['commenttext'] . '">'. $atts['commenttext'] . '</a>'; } } }endif; return '<div class="memberonly">'.$content.'</div>';}add_shortcode( 'com', 'iepress_commentonly_shortcode' );