通過本文章的代碼可以實現隱藏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' );