I've defined a CPT and any non-super admin user on any subsite cannot access it. I cannot figure out what is wrong with my code.
CPT Definition:
// Opportunities
register_post_type(
'opportunities', [
'label' => '',
'labels' => [
'name' => 'Opportunities',
'singular_name' => 'Opportunities',
'add_new_item' => 'Add new Opportunity',
'edit_item' => 'Edit Opportunity',
'new_item' => 'New Opportunity',
'view_item' => 'View Opportunity',
'view_items' => 'View Opportunities',
'search_items' => 'Search Opportunities',
'not_found' => 'No Opportunities found',
'all_items' => 'All Opportunities',
'item_published' => 'Opportunity published',
'item_published_privately' => 'Opportunity published privately',
'item_reverted_to_draft' => 'Opportunity reverted to draft',
'item_scheduled' => 'Opportunity scheduled',
'item_updated' => 'Opportunity updated',
'featured_image' => 'Opportunity Image',
'set_featured_image' => 'Add Opportunity Image',
'remove_featured_image' => 'Remove Opportunity Image',
],
'menu_position' => 11,
'public' => true,
'show_in_menu' => true,
'show_in_rest' => true,
'has_archive' => true,
'menu_icon' => 'dashicons-groups',
'supports' => array('title', 'thumbnail', 'editor'),
'capability_type' => 'opportunities',
'map_meta_cap' => true,
'capabilities' => array(
'edit_post' => 'edit_opportunity',
'read_post' => 'read_opportunity',
'delete_post' => 'delete_opportunity',
'edit_posts' => 'edit_opportunities',
'edit_others_posts' => 'edit_others_opportunities',
'publish_posts' => 'publish_opportunities',
'read_private_posts' => 'read_private_opportunities',
'delete_posts' => 'delete_opportunities',
'delete_private_posts' => 'delete_private_opportunities',
'delete_published_posts' => 'delete_published_opportunities',
'delete_others_posts' => 'delete_others_opportunities',
'edit_private_posts' => 'edit_private_opportunities',
'edit_published_posts' => 'edit_published_opportunities',
),
]
);
Function to add the capabilities to the non-super-admin role:
function add_opportunities_capability_to_admins() {
$sites = get_sites();
foreach ($sites as $site) {
switch_to_blog($site->blog_id);
$admins = get_users(array('role' => 'administrator', 'exclude' => array(get_current_user_id())));
foreach ($admins as $admin) {
if (!is_super_admin($admin->ID)) {
$admin->add_cap('edit_opportunity');
$admin->add_cap('read_opportunity');
$admin->add_cap('delete_opportunity');
$admin->add_cap('edit_opportunities');
$admin->add_cap('read_opportunities');
$admin->add_cap('delete_opportunities');
$admin->add_cap('edit_others_opportunities');
$admin->add_cap('publish_opportunities');
$admin->add_cap('read_private_opportunities');
$admin->add_cap('delete_private_opportunities');
$admin->add_cap('delete_published_opportunities');
$admin->add_cap('delete_others_opportunities');
$admin->add_cap('edit_private_opportunities');
$admin->add_cap('edit_published_opportunities');
}
}
restore_current_blog();
}
}
add_action('after_switch_theme', 'add_opportunities_capability_to_admins');