WordPressで他のユーザーの投稿やメディアを表示しないようにする

TIPS 0 Takuya Kobayashi

WordPressで他のユーザーの投稿やメディアライブラリのファイルを表示しないようにする方法です。

functions.phpに以下を追記:

// postで他者の投稿を見えなくする
function hide_other_posts($wp_query) {
  global $current_screen, $current_user;
    
  if($current_screen->id != 'edit-post') return;
  
  if($current_user->roles[0] == 'administrator') return;

  $wp_query->query_vars['author'] = $current_user->ID;
}
add_action('pre_get_posts', 'hide_other_posts');

// メディアライブラリで他者の投稿を見えなくする
function show_only_authorimage( $where ){
  global $current_user;
    if( $current_user->roles[0] != 'administrator' ){
      if( isset( $_POST['action'] ) && ( $_POST['action'] == 'query-attachments' ) ){
        $where .= ' AND post_author='.$current_user->data->ID;
      }
    }
  return $where;
}
add_filter( 'posts_where', 'show_only_authorimage' );

// postのアクセス限定
function show_owned_posts_only( $views ) {
  global $current_user;
  if($current_user->roles[0] != 'administrator') {  
    unset($views['all']); // すべて
    unset($views['mine']); // 所有
    unset($views['draft']); // 下書き
    unset($views['publish']); // 公開済み
    unset($views['pending']); // 保留中
    unset($views['trash']); // ゴミ箱
  }
  return $views;
}
add_filter('views_edit-post', 'show_owned_posts_only');

// ダッシュボードの項目を消す
function remove_dashboard_widget() {
  global $current_user;
  if( $current_user->roles[0] != 'administrator' ){
    remove_meta_box( 'dashboard_site_health', 'dashboard', 'normal' ); //サイトヘルスステータス
    remove_meta_box( 'dashboard_right_now', 'dashboard', 'normal' ); //概要
    remove_meta_box( 'dashboard_activity', 'dashboard', 'normal' ); //アクティビティ
    remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' ); //クイックドラフト
    remove_meta_box( 'dashboard_primary', 'dashboard', 'side' ); //WordPressニュース
    remove_action( 'welcome_panel', 'wp_welcome_panel' ); //ようこそ
  }
}
add_action('wp_dashboard_setup', 'remove_dashboard_widget' );

// サイドメニューのダッシュボードを消す
function remove_menus() {
  if( $current_user->roles[0] != 'administrator' ){
    remove_menu_page( 'index.php' ); // ダッシュボード
  }
}
add_action( 'admin_menu', 'remove_menus', 999 );

参考サイト:

--
以上