caseproof / members

Members WordPress plugin.
GNU General Public License v2.0
80 stars 35 forks source link

CPT UI #75

Open 3eBoP opened 2 years ago

3eBoP commented 2 years ago

Hello,

I have both Members and Custom Post Type UI plugins installed and I'm facing an issue : In my role manager, and for my users of wp-admin, I can only grant or deny access to posts (globally speaking), but I would like to grant or deny access to custom posts types created, is it possible ?

jechazelle commented 2 years ago

Hi @3eBoP !

To see the different access, you have to add hooks in your functions.php (enable (required) and naming (optional):

/**
 * Add CPT on Members restriction capabilities.
 */
function add_custom_post_type_capability($args, $post_type)
{
  $cpts = [
    'team',
  ];

  foreach ($cpts as $cpt) {
    if ($cpt === $post_type) {
      $slug = $cpt;
      $slug_plural = $slug . 's';

      //$args['map_meta_cap'] = true;
      $args['capability_type'] = $slug_plural;
      $args['capabilities'] = [
        'read_posts' => 'read_' . $slug_plural,
        'read_private_posts' => 'read_private_' . $slug_plural,
        'create_posts' => 'create_' . $slug_plural,
        'publish_posts' => 'publish_' . $slug_plural,
        'edit_posts' => 'edit_' . $slug_plural,
        'edit_others_posts' => 'edit_others_' . $slug_plural,
        'edit_private_posts' => 'edit_private_' . $slug_plural,
        'edit_published_posts' => 'edit_published_' . $slug_plural,
        'delete_posts' => 'delete_' . $slug_plural,
        'delete_others_posts' => 'delete_others_' . $slug_plural,
        'delete_private_posts' => 'delete_private_' . $slug_plural,
        'delete_published_posts' => 'delete_published_' . $slug_plural,
      ];
    }
  }

  return $args;
}

add_filter('register_post_type_args', 'add_custom_post_type_capability', 10, 2);

/**
 * Update labels on Members restriction capabilities.
 */
function update_label_naming() {
  $caps = [
    'create_',
    'delete_others_',
    'delete_',
    'delete_private_',
    'delete_published_',
    'edit_',
    'edit_others_',
    'edit_private_',
    'edit_published_',
    'publish_',
    'read_private_',
    'read_',
    'manage_'
  ];

  $cpts = [
    'teams',
  ];

  foreach ($cpts as $cpt) {
    foreach ($caps as $cap) {
      $slug = $cap . $cpt;
      $label = ucwords(str_replace("_", " ", $cap) . ' ' . str_replace("-", " ", $cpt));
      members_register_cap(
        $slug,
        [
          'label' => __( $label, 'our-theme' ),
        ]
      );
    }
  }
}

add_action( 'members_register_caps', 'update_label_naming' );

You can read this article to read more informations or here to read the documentation about register post type.