WordPressの管理画面でログインユーザー以外のコンテンツを非表示にするには以下のような感じ。
/**
* 管理画面でログインユーザー以外のユーザーのコンテンツを非表示にする。
*/
add_action('pre_get_posts', function( $wp_query ) {
global $current_user;
if( is_admin() && ! current_user_can('edit_others_posts') ) {
$wp_query->set( 'author', $current_user->ID );
}
} );
以上でメディアも含めて、ログインユーザー以外のコンテンツが非表示になります。
でも、以下のような「投稿の件数」は、ログインユーザー以外の記事の件数もカウントされてしまって、ちょっと違和感があります。
この数字をログインユーザーの記事の件数にするには wp_count_posts
というフックを使用します。
/**
* 管理画面のテーブルでログインユーザーの投稿数のみをカウントする。
*
* @param $counts
* @param $type
*
* @return array|object
*/
add_filter( 'wp_count_posts', function ( $counts, $type ) {
if ( is_admin() && ! current_user_can('edit_others_posts') ) {
global $wpdb;
$query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts}
WHERE post_type = %s AND post_author = %d GROUP BY post_status";
$query = $wpdb->prepare( $query, $type, get_current_user_id() );
$results = (array) $wpdb->get_results( $query, ARRAY_A );
$counts = array_fill_keys( get_post_stati(), 0 );
foreach ( $results as $row ) {
$counts[ $row['post_status'] ] = $row['num_posts'];
}
return (object) $counts;
}
return $counts;
}, 10, 3 );
カスタム投稿タイプだと edit_others_posts
の部分は edit_others_xxxs
みたいなことになることもあるので、適時修正してください。