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