0

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');

2 Answers 2

1

Here's how I'd handle it (mostly you're right, and the tweak in your answer to use init gets you closer, but — as you've discovered — doing a bunch of switch_to_blog() / restore_current_blog() calls on every single page load is costly).

function add_opportunities_capability_to_admins() {

    // Set up the needed capabilities.
    $capabilities = array(
        'edit_opportunity',
        'read_opportunity',
        'delete_opportunity',
        'edit_opportunities',
        'read_opportunities',
        'delete_opportunities',
        'edit_others_opportunities',
        'publish_opportunities',
        'read_private_opportunities',
        'delete_private_opportunities',
        'delete_published_opportunities',
        'delete_others_opportunities',
        'edit_private_opportunities',
        'edit_published_opportunities',
    );
    $sites = get_sites();

    // Gets the current state of affairs.
    $current_permission_state = md5( json_encode( array( $capabilities, $sites ) ) );
    $last_saved_permission_state = get_site_option( 'my_permission_state', '' );

    // If things have changed, we re-run the permission updates.
    if ( $current_permission_state !== $last_saved_permission_state ) {

        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)) {
                    foreach ( $capabilities as $capability ) {
                        $admin->add_cap( $capability );
                    }
                }
            }

            restore_current_blog();
        }

        // Save the current state so we don't have to run this again for a while.
        update_site_option( 'my_permission_state', $current_permission_state );
    }
}

add_action('init', 'add_opportunities_capability_to_admins');

Note: This code is untested. Try it on a test site before putting it into production.

References

1
  • Thanks for the response. I'll keep this mind as I do a lot of work on this site and I expect to create more users for CPTs... for whatever reason they like to have a user for each CPT... I got it working now by doing what I had described, just running it once on init then commenting out it out immediately.. not the ideal method but it worked! I like the approach here with the capabilities check vs manually adding/removing the action Commented Dec 30, 2023 at 17:51
0

Changing the action to init instead of after_switch_theme solved the problem.

That significantly slowed the backend of the site down that said it only needs to run once then everything is saved in the DB and it doesn't need to run again.

1
  • 1
    Running it on after_switch_theme means it'll only run when you switch themes. Running on init means it'll run on every single page load. My recommendation would be to run the function on init but add a network setting (aka site option) once it's run; then check that network setting at the start of add_opportunities_capability_to_admins() and if it's already been done, return instead of running the (expensive) switch_to_blog() / restore_current_blog() calls. Let me know if you want a code sample.
    – Pat J
    Commented Dec 22, 2023 at 18:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.