管理画面内で表示内容を制限する方法
他者投稿を編集する権限を持たないユーザに対して、/wp-admin上で自分の投稿だけしか確認できないようにする方法。
例えば複数人でWordPressサイトを運営していて、一部のユーザに対して表示内容を制限したいときに使えるかもしれない。
ちなみに他者投稿を編集する権限を持っているかは「current_user_can('edit_others_posts')」で判定できる。
実装例
メディアライブラリ
自分がアップロードしたメディアファイルしか表示できないように制限
function display_only_self_uploaded_attachments($query){
if(is_user_logged_in() && !current_user_can('edit_others_posts')){
$query['author'] = get_current_user_id();
}
return $query;
}
add_action('ajax_query_attachments_args', 'display_only_self_uploaded_attachments');
投稿一覧
自分の投稿しか表示できないように制限
function display_only_self_posts($query){ if(is_user_logged_in() && current_user_can('edit_others_posts')) return; if(is_admin() && $query->is_main_query()){ $query->set('author', get_current_user_id()); } } add_action('pre_get_posts', 'display_only_self_posts');
表示するカウント数を自分の投稿だけに制限
function count_only_self_posts($counts, $type='post', $perm=''){ global $wpdb; if(!post_type_exists($type)) return new stdClass; $cache_key = _count_posts_cache_key($type, $perm).'_author'; $counts = wp_cache_get($cache_key, 'counts'); if(!$counts){ $query = "SELECT post_status, COUNT(*) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s"; if(is_user_logged_in() && !current_user_can('edit_others_posts')){ $query .= $wpdb->prepare(" AND (post_author = %d)", get_current_user_id()); } $query .= ' GROUP BY post_status'; $results = (array) $wpdb->get_results($wpdb->prepare($query, $type), ARRAY_A); $counts = array_fill_keys(get_post_stati(), 0); foreach($results as $row){ $counts[$row['post_status']] = $row['num_posts']; } $counts = (object) $counts; wp_cache_set($cache_key, $counts, 'counts'); } return $counts; } add_filter('wp_count_posts', 'count_only_self_posts', 10, 3);