admin管理员组文章数量:1126314
I am in the process of creating a form for a user to fill out to create a listing request which creates a CPT post and user record.
In this process, I want to copy the subscriber role, rename it 'username-role' and assign it to the new user.
I want to then allow the new role 'username-role' the edit_post capability on that one single CPT post they created.
Basically, I want people to come to the website, create a listing and then be able to log in and edit that listing (and only that listing)
How can I give a user role and capabilities object permission to edit one single CPT post only?
I am in the process of creating a form for a user to fill out to create a listing request which creates a CPT post and user record.
In this process, I want to copy the subscriber role, rename it 'username-role' and assign it to the new user.
I want to then allow the new role 'username-role' the edit_post capability on that one single CPT post they created.
Basically, I want people to come to the website, create a listing and then be able to log in and edit that listing (and only that listing)
How can I give a user role and capabilities object permission to edit one single CPT post only?
Share Improve this question asked Jan 19, 2024 at 7:09 php-b-graderphp-b-grader 4182 gold badges7 silver badges21 bronze badges 4 |1 Answer
Reset to default -2Add code - your current active theme's functions.php
file or in a custom plugin:
// Step 1: Create a New Role Based on Subscriber
function create_custom_role() {
// Check if the role doesn't already exist
if (!get_role('username-role')) {
// Get the capabilities of the Subscriber role
$subscriber_role = get_role('subscriber');
$capabilities = $subscriber_role->capabilities;
// Create a new role based on Subscriber
add_role('username-role', 'Username Role', $capabilities);
}
}
add_action('init', 'create_custom_role');
// Step 2: Assign the New Role to the User
function assign_custom_role_to_user($user_id) {
$user = new WP_User($user_id);
$user->set_role('username-role');
}
add_action('user_register', 'assign_custom_role_to_user');
// Step 3: Grant Edit Post Capability for the CPT
function grant_edit_post_capability($post_id, $post, $update) {
// Check if it's the desired CPT post type
if ($post->post_type === 'your_cpt') {
// Please replace 'your_cpt' with the actual slug of your custom post type
// Get the user who created the post
$user_id = $post->post_author;
// Get the user's role
$user = new WP_User($user_id);
$user->add_cap('edit_post', $post_id);
}
}
add_action('save_post', 'grant_edit_post_capability', 10, 3);
本文标签: Allowing a CPT post to be edited by a single user role
版权声明:本文标题:Allowing a CPT post to be edited by a single user role 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736684676a1947598.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
edit_others_posts
capability. – Jacob Peattie Commented Jan 19, 2024 at 8:33