Hide specific admin users’ posts

Try this – rather than redo all the hard work that WordPress does for the view links, just calculate all the posts for the admin you want to “hide” and subtract from the existing post counts:

function wpse_229427_get_hidden_admin_id() {
    return 3; // You could make this a setting or return a value conditionally
}

function wpse_229427_hide_admin_posts( $wp_query ) {
    if ( is_admin() && ! current_user_can( 'edit_others_posts' ) && ! $wp_query->get( 'author' ) ) {
        $wp_query->set( 'author__not_in', [ wpse_229427_get_hidden_admin_id() ] );
    }
}

add_action( 'pre_get_posts', 'wpse_229427_hide_admin_posts' );

function wpse_229427_adjust_counts( $counts, $type ) {
    if ( $type === 'post' && is_admin() && ! current_user_can( 'edit_others_posts' ) ) {
        global $wpdb;

        $admin_id = wpse_229427_get_hidden_admin_id();
        $items    = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT post_status, COUNT( * ) AS `count` FROM {$wpdb->posts} WHERE post_type="post" AND post_author = %d GROUP BY post_status",
                $admin_id
            )
        );

        foreach ( $items as $item ) {
            if ( isset( $counts->{$item->post_status} ) )
                $counts->{$item->post_status} -= $item->count;
        }
    }

    return $counts;
}

add_filter( 'wp_count_posts', 'wpse_229427_adjust_counts', 10, 2 );

Leave a Comment