Skip to content

Instantly share code, notes, and snippets.

@bagerathan
Created August 23, 2021 04:25
Show Gist options
  • Save bagerathan/eed16b058842b022477e7c40615a652d to your computer and use it in GitHub Desktop.
Save bagerathan/eed16b058842b022477e7c40615a652d to your computer and use it in GitHub Desktop.
[Restrict access to custom posts based on role] #wp
//create a new role
function psp_add_project_management_role() {
add_role('psp_project_manager',
'Project Manager',
array(
'read' => true,
'edit_posts' => false,
'delete_posts' => false,
'publish_posts' => false,
'upload_files' => true,
)
);
}
register_activation_hook( __FILE__, 'psp_add_project_management_role' );
//map capabilities
add_action( 'init', 'psp_register_cpt_projects');
function psp_register_cpt_projects() {
$args = array(
'label' => __( 'psp_projects', 'psp_projects' ),
'description' => __( 'Projects', 'psp_projects' ),
'labels' => $labels,
'supports' => array( 'title', 'comments', 'revisions', ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'rewrite' => $rewrite,
'capability_type' => array('psp_project','psp_projects'),
'map_meta_cap' => true,
);
register_post_type( 'psp_projects', $args );
}
//add custom capabilities for the role
add_action('admin_init','psp_add_role_caps',999);
function psp_add_role_caps() {
// Add the roles you'd like to administer the custom post types
$roles = array('psp_project_manager','editor','administrator');
// Loop through each role and assign capabilities
foreach($roles as $the_role) {
$role = get_role($the_role);
$role->add_cap( 'read' );
$role->add_cap( 'read_psp_project');
$role->add_cap( 'read_private_psp_projects' );
$role->add_cap( 'edit_psp_project' );
$role->add_cap( 'edit_psp_projects' );
$role->add_cap( 'edit_others_psp_projects' );
$role->add_cap( 'edit_published_psp_projects' );
$role->add_cap( 'publish_psp_projects' );
$role->add_cap( 'delete_others_psp_projects' );
$role->add_cap( 'delete_private_psp_projects' );
$role->add_cap( 'delete_published_psp_projects' );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment