WordPress前台文章页用户只能看见自己的评论

老白博客今天跟大家分享的WordPress技巧是纯代码实现“WordPress前台文章页用户只能看见自己的评论”。效果是:对于每一个登录用户,在文章页只能看到自己的评论,看不见其他人的评论;而对于网站管理员,则能够看到所有评论(这个功能很奇怪,不过功能嘛,有需求就有市场,可能还是朋友需要)

WordPress前台文章页用户只能看见自己的评论

1.思路来源

这个是在搬主题和WordPress大学两位大佬那里看到的,是用于设置WordPress后台编辑角色的权限设定的,然后才有了本文的WordPress前台用户评论设定,两位大佬的代码如下

1.1 后台仅查看评论

WordPress大学链接:https://www.wpdaxue.com/show-comments-authors-own-posts.html

功能:限制用户只能看到自己文章下的评论,将下面的代码添加到主题根目录下的 functions.php 即可:

function wpdx_get_comment_list_by_user($clauses) {
	if (is_admin()) {
		global $user_ID, $wpdb;
		$clauses['join'] = ", wp_posts";
		$clauses['where'] .= " AND wp_posts.post_author = ".$user_ID." AND wp_comments.comment_post_ID = wp_posts.ID";
	};
	return $clauses;
};
if(!current_user_can('edit_others_posts')) {
	add_filter('comments_clauses', 'wpdx_get_comment_list_by_user');
}

1.2 后台仅查看评论和文章

搬主题链接:https://www.banzhuti.com/wordpress-only-view-own-comments.html

代码功能:限制普通用户在WordPress后台中只能查看自己相关的评论和文章信息

function wpdx_get_comment_list_by_user($clauses) {
   
if (is_admin()) {
   
global {
   mathJaxContainer[0]}wpdb;
$clauses['join'] = ", wp_posts";
{
   mathJaxContainer[1]}user_ID." AND wp_comments.comment_post_ID = wp_posts.ID";
};
return $clauses;
};
if(!current_user_can('edit_others_posts')) {
   
add_filter('comments_clauses', 'wpdx_get_comment_list_by_user');
}


function bzt_parse_query_useronly( $wp_query ) {
   
if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/edit.php' ) !== false ) {
   
if ( !current_user_can( 'add_user' ) ) {
   
global $current_user;
{
   mathJaxContainer[2]}current_user->id );
}
}
}
add_filter('parse_query', 'bzt_parse_query_useronly' );

2.前台只能看自己评论

上述两位大佬的代码都是作用于WordPress后台,更明确的说,是WordPress用户中的“作者角色”,老白这里给出一个针对WordPress前台的“用户”的代码,

2.1 功能代码

将下面的代码,加到自己主题的function.php文件

此处为隐藏内容,评论后查看

2.2 演示效果和测试地址

地址:https://test.xcbtmw.com/252.html

效果说明:非登录用户看不到任何评论、登录用户只能看到自己的评论

测试账号用户名:1

账号密码:1

2.3 注意事项

既然设置了只能查看用户自己的评论,就需要关闭访客评论功能。

WordPress仪表盘—设置—讨论设置,勾选“用户必须注册并登录才可以发表评论”