LoginSignup
1
1

More than 5 years have passed since last update.

WordPressでアップロードしたメディアを投稿者自身にしか表示させたくない。

Last updated at Posted at 2017-10-29

2017-08-09 18:13:43

投稿者が不特定多数いる場合、アップロードした画像を投稿者自身にしか表示させたくないことがあるかと思います。

今回それを行いたいのは

contributor(寄稿者)とauthor(投稿者)だったので

functions.php
function my_media_author_query( $wp_query ) {
if (! preg_match('/wp-admin\/(?:upload|media-upload|admin-ajax).php/', $_SERVER['REQUEST_URI']) ) {
  return;
}

  global $current_user;
  $user_roles = $current_user->roles;
  $user_role = array_shift($user_roles);
  if($user_role==='contributor'||$user_role==='author'){
      $wp_query->set( 'author', $current_user->id );
  }
}
add_filter('pre_get_posts', 'my_media_author_query' );

当初海外のQ&Aサイトに投稿されていたのは上記のようなコードでした。
とりあえずうまく行ったように見えるのは落とし穴。

その後クライアントからAdvancedCustomField(ACF)で作ったハズのユーザープロフィールが変更されない、とのご指摘をうけました。

色々問題を切り分けていくと、どうもこのコードが原因のよう。
そもそもadmin-ajax.phpをACFはつかっているようで、そのフィールドの抽出作業の過程で上記のコードでは作成者でフィルタリングされてしまう為に表示されなくなる模様。

結果色々工夫した挙句、

if($wp_query->query_vars['post_type']!=='attachment'){
return;
}
を加えて

functions.php
function my_media_author_query( $wp_query ) {

//追加! post_typeがattachment以外はreturn 
if($wp_query->query_vars['post_type']!=='attachment'){
  return;
}

if (! preg_match('/wp-admin\/(?:upload|media-upload|admin-ajax).php/', $_SERVER['REQUEST_URI']) ) {
  return;
}

  global $current_user;
  $user_roles = $current_user->roles;
  $user_role = array_shift($user_roles);
  if($user_role==='contributor'||$user_role==='author'){
      $wp_query->set( 'author', $current_user->id );
  }
}
add_filter('pre_get_posts', 'my_media_author_query' );

でメディア画像の抽出時の動作の時のみフィルタリングさせる事に成功しました。

そもそもコードが不完全だったようです。。
あまり鵜呑みにしたらダメですね。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1