3

In my code i have a custom post type job.I created a role called job manager.Now i want to give permissions to add,edit ,delete a job for job manager.Only he can access job post type.hoe w to achieve this....

I tried to create job manager role by following code

          function add_job_manager_role(){
           add_role(
                'job_manager',
                 'Job Manager',
                   array(
                    'read'          => true,
                    'edit_posts'    => false,
                    'delete_posts'  => false,
                    'publish_posts' => false,
                    'upload_files'  => true
           )
        );
     }
   add_action( 'admin_init', 'add_job_manager_role', 4 ); 

how to give permissions to job manager to add ,delete,edit custom post type job

any help greatly appreciated .Thanks in advance ....

4

1 回答 1

2

添加角色时,您还必须添加功能,如下所示:

/**
add CPT capabilites to Role
*/
add_action('admin_init','o99_add_role_caps',999);

function o99_add_role_caps() {

    $role = get_role('my_role');      // ex. job_manager         
    $role->add_cap( 'read_my_CPT');
    $role->add_cap( 'edit_my_CPT' );
    $role->add_cap( 'edit_my_CPT' );
    $role->add_cap( 'edit_other_my_CPT' );
    $role->add_cap( 'edit_published_my_CPT' );
    $role->add_cap( 'publish_my_CPT' );
    $role->add_cap( 'read_private_my_CPT' );
    $role->add_cap( 'delete_my_CPT' );


}

my_CPT当然是您的自定义帖子类型,在创建时您提供了功能参数或修改它,您执行了以下操作:

function change_capabilities_of_CPT( $args, $post_type ){

 // Do not filter any other post type
 if ( 'my_CPT' !== $post_type ) { // my_CPT == Custom Post Type == 'job' or other

     // if other post_types return original arguments
     return $args;

 }


// This is the important part of the capabilities 
/// which you can also do on creation ( and not by filtering like in this example )


 // Change the capabilities of my_CPT post_type
 $args['capabilities'] = array(
            'edit_post' => 'edit_my_CPT',
            'edit_posts' => 'edit_my_CPT',
            'edit_others_posts' => 'edit_other_my_CPT',
            'publish_posts' => 'publish_my_CPT',
            'read_post' => 'read_my_CPT ',
            'read_private_posts' => 'read_private_my_CPT',
            'delete_post' => 'delete_my_CPT'
        );

  // Return the new arguments
  return $args;

}

编辑我

欲了解更多信息:

为了能够控制 CPT,capabilities每个操作都涉及其他几个操作。

举例来说,为了publish_my_CPT编辑,您将需要edit_my_CPT&& edit_other_my_CPT&& read_my_CPT&&read_private_my_CPT等等。请查看Codex 中的功能,并且通过发布的代码,您可以将_my_CPT(例如 -_job或任何 CPT )添加到这些功能中,从而使您能够实现他想要的结果。

于 2019-09-16T09:09:28.670 回答