What is the correct way of validating running code when a particular role accesses a screen?

Reducing the number of checks increases the performance of your code, so yes, check is_user_logged_in() and current_user_can() as few times as you can. For executing functions depending on the admin page, I’d probably attach callbacks to load-{$pagenow} hook (untested): function wpse417218_do_something_for_edit_page() { if ( ‘page’ !== get_current_screen()->id ) { return; } if ( ! current_user_can( … Read more

Non-super-admin users cannot access CPT even though I have explicitly added the capabilities to the user role

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’, … Read more

How to allow Contributors to edit their own posts, whilst still needing to be reviewed by an admin?

Steps for setting edited posts by contributors to “pending review”: 1. Adjust Contributor Capabilities Your modifications to the contributor role are appropriate for allowing them to edit their posts. Ensure they can edit posts but cannot publish them. 2. Automatically Revert Posts to “Pending Review” on Edit Add the following code to your functions.php. This … Read more

Redirecting by role from a button

You could try something like the code below. <?php /** * Use the two lines below if the user_id is not available * via get_current_user_id at this point in code execution. * * $user_id = apply_filters( ‘determine_current_user’, false ); * wp_set_current_user( $user_id ); */ $current_user_id = get_current_user_id(); $user_data = get_userdata( $current_user_id ); $user_roles = $user_data->roles; … Read more

How to add custom user role into wordpress

Example: add_role(‘student’, __( ‘Student’), array( ‘read’ => true, // Allows a user to read ‘create_posts’ => false, // Allows user to create new posts ‘edit_posts’ => false, // Allows user to edit their own posts ‘edit_others_posts’ => false, // Allows user to edit others posts too ‘publish_posts’ => false, // Allows the user to publish … Read more