0

I am trying to assign privileges on posts on a per post basis.

Essentially, I have a custom post type which have authors. They can edit their own posts.

I then have another role, which should be able to edit a subset of those posts bases on a custom field or taxonomy.

I can filter out the posts that appear in the backend using pre_get_posts, and applying a query based on the custom field. However I need to limit specifically edit privileges for each post.

Does anyone know if it's possible to apply an "editable" filter per post rather than a blanket privilege based on the role?

Thanks!

1 Answer 1

0

I believe with the help of remove_post_type_support you can achieve this. But first you need to keep an user meta with the list of posts IDs he/she will be able to edit. And you can achieve this with this below function-

update_user_meta( $user_id, $meta_key, $meta_value, $prev_value )

So whenever a post will be loaded you can check the array of editable post IDs for his/her and based on that you can invoke or revoke the post type support. Have a look at the below code-

// Don't stick with the `admin_init` hook only. If it doesn't work please try with other hooks also
add_action( 'admin_init', 'codemascot_invoke_or_revoke_post_supports' );
function codemascot_invoke_or_revoke_post_supports() {
    // By setting the last parameter from `false` to `true` you will get return an array.
    // Here I'm using get_current_user_id() to get current logged in user ID.
    $editable_posts = get_user_meta( get_current_user_id(), $meta_key, true );
    // change the post type support based on your custom user permission
    if ( ! in_array( get_the_ID(), $editable_posts ) ) {
        remove_post_type_support( 'post', 'editor' );
    }
}

NB. You can store the user IDs with the permission to edit the post in post meta too. But querying a post meta has some drawbacks as post meta table usually has the higher probability of growth than user meta which may cause slow query.

This above code block is just an idea or concept which is not tested in WordPess environment. So, some important precaution are-

  1. Don't stick with the admin_init hook only. If it doesn't work please try with other hooks also and let me know. I'll update my answer.
  2. Please read the function documentations for further info about the functions mentioned here,
  3. Test the code before putting it in production.

Hope my answer helps you.

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.