現在、サイトへ登録したユーザーが閲覧できるホーム画面(wp-admin/index.php)で
メニューから「コメント」を選択すると
他ユーザーの記事についたコメントが全て表示されてしまっています。
サイトオーナー以外は、
他人の記事についたコメントは閲覧不可にしたいのですが、
どのような処理を行えばよいのでしょうか?
他人の書いた記事投稿を閲覧できないようにする方法を参考に
色々調べた結果、
functions.phpでpre_get_commentsを使用し
コメント取得用のクエリを変更すれば良いと思うのですが、
なかなか方法が見当たらず躓いております。
これが他人の記事を閲覧できないようにする方法です。
PHP
1if (!current_user_can('level_10')) { 2function exclude_other_posts( $wp_query ) { 3 4 if ( isset( $_REQUEST['post_type'] ) && post_type_exists( $_REQUEST['post_type'] ) ) { 5 $post_type = get_post_type_object( $_REQUEST['post_type'] ); 6 $cap_type = $post_type->cap->edit_other_posts; 7 } else { 8 $cap_type = 'edit_others_posts'; 9 } 10 11 if ( is_admin() && $wp_query->is_main_query() && ! $wp_query->get( 'author' ) && ! current_user_can( $cap_type ) ) { 12 $user = wp_get_current_user(); 13 //※ 14 $wp_query->set( 'author', $user->ID ); 15 } 16 17} 18add_action( 'pre_get_posts', 'exclude_other_posts' ); 19}
//※
set($query_var, $value)
指定されたクエリ変数を任意の値に設定する。
たぶん、管理者(author)から今アクセスしているユーザーのIDに
該当する記事を返しているので閲覧制限を実現できているのかと思います。
コメントも現在閲覧しているユーザーのIDを元にした
記事を表示できればいいので
PHP
1if (!current_user_can('level_10')) { 2 3 function exclude_other_comments( $wp_query ) { 4 5 if ( isset( $_REQUEST['post_type'] ) && post_type_exists( $_REQUEST['post_type'] ) ) { 6 $post_type = get_post_type_object( $_REQUEST['post_type'] ); 7 $cap_type = $post_type->cap->edit_other_posts; 8 print "パターン1"; 9 } else { 10 $cap_type = 'edit_others_posts'; 11 print "パターン2"; 12 } 13 14 if ( is_admin() && $wp_query->is_main_query() && ! $wp_query->get( 'author' ) && ! current_user_can( $cap_type ) ) { 15 $user = wp_get_current_user(); 16 $wp_query->set( 'author', $user->ID ); 17 print "パターン3"; 18 } 19 20 $wp_query->set( 'author', 3 ); 21 print "実行"; 22 } 23 24 add_action( 'pre_get_comments', 'exclude_other_comments' ); 25}
pre_get_commentsをフックに同じように記述しているのですが、
「パターン2」の処理にしかなりません。
「パターン1」を通らないということは、
$_REQUEST['post_type']の段階で問題があるということかと思います。
POSTに問題があるということがいまいちイメージできないので
$_REQUEST['post_type']の中身を調べようと思いましたが、
出力の方法が分からず断念しました。
また、最終的にcurrent_user_can()からユーザーのIDを取得し
該当ユーザーの記事から更にコメントのついている記事を表示できる
クエリにすればいいと思うので
$wp_queryの中身を調べ、試行錯誤でクエリを組み立てようと思いましたが、
こちらも出力の方法が分からず断念しました。
やり方が分かる方がいらっしゃいましたら
お教え願えますでしょうか?
よろしくお願い致します。
wordpressのバージョン 4.9.5–ja
PHPのバージョン 7.1.2
回答1件
あなたの回答
tips
プレビュー