How to assign specific users the capability to edit specific pages / posts / custom post types

I can suggest another method.

First of all: grant full access to projects post type (Example).

At the user profile add allowed posts’ id.

Then use below filter to restrict access if post id isn’t allowed.

function allow_user_to_edit_cpt_filter( $capauser, $capask, $param){

    global $wpdb;

    $allowed_posts_id_for_current_user = array( '29', '30' ); // you need to get these ids yourself
    $post = get_post( $param[2] );

    // If current post isn't allowed then delete edit and delete capabilities
    if( !in_array( $post->ID, $allowed_post_type_ids ) ){
        if( ( $param[0] == "edit_projects") || ( $param[0] == "delete_projects" ) ) { // Change to yours capabilities
            foreach( (array) $capask as $capasuppr) {
               if ( array_key_exists($capasuppr, $capauser) ) {
                  $capauser[$capasuppr] = 0;
               }
            }
        }
    }

    return $capauser;
}
add_filter('user_has_cap', 'allow_user_to_edit_cpt_filter', 100, 3 );

Leave a Comment