WordPress - 自定义文章类型,自定义角色,自定义权限

10

我遇到了一个问题,即如何给自定义角色分配自定义帖子类型的自定义能力。

问题是我想要移除我的自定义帖子类型的“添加新项”选项(不使用CSS hack或取消菜单项)。我已经找到了很多解决方案,但它们都不完美地解决了我的问题。

最接近我想要的解决方案是这个:

register_post_type( 'custom_post_type_name', array(
  'capability_type' => 'post',
  'capabilities' => array(
    'create_posts' => 'do_not_allow', // false < WP 4.5, credit @Ewout
  ),
  'map_meta_cap' => true, // Set to `false`, if users are not allowed to edit/delete existing posts
));

这段代码会移除“添加新内容”的链接,但是会给默认的文章赋予权限。请注意以上代码的第2行。如果我将其更改为自定义文章类型的权限,则它将停止工作,我甚至无法访问文章页面。

需要记住的一件事是,我正在使用自定义角色,默认只有阅读权限。

如果我也分配编辑文章的权限,那么我的目标就实现了,但是用户也可以访问文章和评论,这不是我想要的。

Woocommerce正在这样做。我深入研究woocommerce代码,并在注册其产品和订单时添加了此行。

'capabilities'        => array( 'create_posts' => 'do_not_allow' ),

而且一切都按照我的意愿进行。我整天探索了WooCommerce代码,但找不到它是如何做到这一点的。有其他人可以用另一双眼睛帮助我吗?:)

非常感谢。谢谢。


你尝试将 'create_posts' 设置为 null 或空字符串了吗? - Gaurav
是的,我用相同的结果完成了。 - Shahbaz A.
我认为你把它设置在了错误的位置。你应该给这个能力一个独特的名称,然后将其添加到各自角色的能力数组中,或者在定义自定义角色时将相应的能力设置为false。请参考https://dev59.com/2msy5IYBdhLWcg3w9ixu?rq=1 - Gaurav
请问您能否在问题中提供一些更多的信息,例如,您真正想要实现什么?目前我从这里猜测的是,您尝试隐藏CPT添加新功能以针对特定用户角色?但您还给了该用户角色编辑和修改、重新编辑能力/权限? - mlimon
@Gaurav 不允许是正确的做法,而不是像你建议的设置为false。我已经尝试过所有这些事情了。 - Shahbaz A.
@mlbd 你是对的。那正是我想做的。 - Shahbaz A.
2个回答

3

我已经向您提到,请给我们更多关于您想要做的计划的细节?

这是我认为会对您有帮助的解决方案。

如果您想使用map_meta_cap => true,那么您需要更改capability_type为您自己的类型,请参见更多信息:https://codex.wordpress.org/Function_Reference/register_post_type#capability_type

但是,如果您设置了自己的capability_type值,则需要将能力添加到您想要添加的用户角色中。

下面是一个完整的示例。

if ( !class_exists( 'WPSE64458_CPT_Register' ) ) {
  class WPSE64458_CPT_Register {

    function __construct() {
      add_action( 'init', array( $this, 'wpse64458_register_post_types' ), 5 );
      add_action( 'admin_init', array( $this, 'wpse64458_add_caps' ), 5 );
      add_filter( 'register_post_type_args', array( $this, 'wpse64458_modify_cpt_registry' ) , 10, 2 );

    }

    /**
     * Register core post types.
     */
    public function wpse64458_register_post_types() {

      if ( ! is_blog_installed() || post_type_exists( 'member' ) ) {
        return;
      }

      register_post_type( 'member',
        apply_filters( 'wpse64458_callb_post_type_member',
          array(
            'labels'              => array(
              'name'                  => __( 'Members', 'domaintext' ),
              'singular_name'         => __( 'Member', 'domaintext' ),
              'all_items'             => __( 'All Members', 'domaintext' ),
              'menu_name'             => _x( 'Members', 'Admin menu name', 'domaintext' ),
              'add_new'               => __( 'Add New', 'domaintext' ),
              'add_new_item'          => __( 'Add new member', 'domaintext' ),
              'edit'                  => __( 'Edit', 'domaintext' ),
              'edit_item'             => __( 'Edit member', 'domaintext' ),
              'new_item'              => __( 'New member', 'domaintext' ),
              'view'                  => __( 'View member', 'domaintext' ),
              'view_item'             => __( 'View member', 'domaintext' ),
              'search_items'          => __( 'Search members', 'domaintext' ),
              'not_found'             => __( 'No members found', 'domaintext' ),
              'not_found_in_trash'    => __( 'No members found in trash', 'domaintext' ),
              'parent'                => __( 'Parent member', 'domaintext' ),
              'featured_image'        => __( 'Member image', 'domaintext' ),
              'set_featured_image'    => __( 'Set member image', 'domaintext' ),
              'remove_featured_image' => __( 'Remove member image', 'domaintext' ),
              'use_featured_image'    => __( 'Use as member image', 'domaintext' ),
              'insert_into_item'      => __( 'Insert into member', 'domaintext' ),
              'uploaded_to_this_item' => __( 'Uploaded to this member', 'domaintext' ),
              'filter_items_list'     => __( 'Filter members', 'domaintext' ),
              'items_list_navigation' => __( 'Members navigation', 'domaintext' ),
              'items_list'            => __( 'Members list', 'domaintext' ),
            ),
            'public'              => true,
            'show_ui'             => true,
            'capability_type'     => 'member',
            'map_meta_cap'        => true,
            'menu_icon'          => 'dashicons-groups',
            'publicly_queryable'  => true,
            'exclude_from_search' => false,
            'hierarchical'        => false, // Hierarchical causes memory issues - WP loads all records!
            'rewrite'            => array( 'slug' => 'member' ),
            'query_var'           => true,
            'supports'            => array( 'title', 'editor', 'thumbnail', 'excerpt' ),
            'has_archive'         => 'members',
            'show_in_nav_menus'   => true,
            'show_in_rest'        => true,
          )
        )
      );

    } // end of wpse64458_register_post_types


    /**
     * Get capabilities.
     *
     * @return array
     */
     private function wpse64458_set_caps() {
      $capabilities = array();

      $capability_types = array( 'member' );

      foreach ( $capability_types as $capability_type ) {

        $capabilities[ $capability_type ] = array(
          // Post type
          "edit_{$capability_type}",
          "read_{$capability_type}",
          "delete_{$capability_type}",
          "edit_{$capability_type}s",
          "edit_others_{$capability_type}s",
          "publish_{$capability_type}s",
          "read_private_{$capability_type}s",
          "delete_{$capability_type}s",
          "delete_private_{$capability_type}s",
          "delete_published_{$capability_type}s",
          "delete_others_{$capability_type}s",
          "edit_private_{$capability_type}s",
          "edit_published_{$capability_type}s",

          // Terms
          // "manage_{$capability_type}_terms",
          // "edit_{$capability_type}_terms",
          // "delete_{$capability_type}_terms",
          // "assign_{$capability_type}_terms",

        );
      }

      return $capabilities;
    }

    /*
      Add Capability
     */
    public function wpse64458_add_caps(){

      global $wp_roles;

      if ( ! class_exists( 'WP_Roles' ) ) {
        return;
      }

      if ( ! isset( $wp_roles ) ) {
        $wp_roles = new WP_Roles();
      }

      $capabilities = $this->wpse64458_set_caps();

      foreach ( $capabilities as $cap_group ) {
        foreach ( $cap_group as $cap ) {
          $wp_roles->add_cap( 'editor', $cap );
          $wp_roles->add_cap( 'administrator', $cap );
        }
      }
    }

    public function wpse64458_modify_cpt_registry( $args, $post_type ){

      // Do not filter any other post type
      if ( 'member' !== $post_type ) {

        // Give other post_types their original arguments
        return $args;

      }

      if( current_user_can('editor') ) {
        $args['capabilities']['create_posts'] = false;
      }

      // Give the custom-css-js post type it's arguments
      return $args;

    }


  }
}

然后用new WPSE64458_CPT_Register();继承这个类。

通过这个例子,我禁用编辑角色来添加新成员文章功能。您可以修改任何您喜欢的内容,或者您也可以使用其他方法来实现。但是您之前提到您已经尝试过按照WooCommerce的方式进行操作,实际上他们也是这样做的。

希望这对您有所帮助。

HappyCodding!


非常感谢您提供如此出色和详细的答案。但是我已经完成了这个任务。正如我在问题中提到的,我需要为自定义角色设置只读权限。如果自定义角色具有edit_posts功能,则可以与任何默认角色或自定义角色一起使用。但是我不想给自定义角色edit_posts功能。就是这样。除此之外,其他所有内容都与您编写和解释的完全相同。希望这能澄清您所问的问题。 - Shahbaz A.
很高兴听到你已经完成了这个任务。不过,如果你真的只想给予读取权限而不想给予其他能力,那么我真的不知道还有什么控制权可以操作了?如果我不给用户编辑文章或自定义文章类型的角色,那么我在这里就找不到任何问题了。祝你编码愉快! :) - mlimon
那就是问题所在。我就是想不出这里缺了什么。我想也许别人能找出来。除非我给予edit_posts权限,否则它无法工作。如果我给了它,那么一切都完美地运行。我想给并且已经给了edit_cpt,但我不想给edit_posts。 - Shahbaz A.
我授予你这个悬赏,因为你已经进行了诚实的尝试并且你的回答是有效的。但是,由于它没有解决我的问题,我无法接受它。干杯。 - Shahbaz A.

3
您可以使用以下脚本将特定用户角色限制在自定义文章中: 添加自定义角色
add_action('init','add_my_custom_role');
    function add_my_custom_role() {

     add_role('my_custom_role',
                'Custom Role',
                array(
                    'read' => true,
                    'edit_posts' => false,
                    'delete_posts' => false,
                    'publish_posts' => false,
                    'upload_files' => false,
                    'publish_posts' => false,
                    'create_posts' => false, 
                )
            );
       }

注册自定义文章。
add_action( 'init', 'my_custom_post_type');
function my_custom_post_type() {
     $args = array(
 'label'               => __( 'Custom post', 'custom-text-domain' ),
 'description'         => __( 'Custom post', 'custom-text-domain' ),
 'labels'              => $labels,
 'supports'            => array( 'title', 'comments', 'revisions', ),
 'hierarchical'        => false,
 'public'              => true,
 'show_ui'             => true,
 'rewrite'             => $rewrite,
                        'capability_type'     => array('custom_post','custom_post'),
                        'map_meta_cap'        => true, // Set to `false`, if users are not allowed to edit/delete existing posts 
 );
 register_post_type( 'custom_post', $args );
}

根据角色允许用户在文章上具有某些能力。
    add_action('admin_init','custom_post_add_role_caps',999);
        function custom_post_add_role_caps() {

     // Add the roles you'd like to administer the custom post types
     $roles = array('my_custom_role','editor');

     // 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_custom_post');
                  $role->add_cap( 'read_private_custom_post' );
                  $role->add_cap( 'edit_custom_post' );
                  $role->add_cap( 'edit_custom_post' );
                  $role->add_cap( 'edit_others_custom_post' );
                  $role->add_cap( 'edit_published_custom_post' );
                  $role->add_cap( 'publish_custom_post' );
                  $role->add_cap( 'delete_others_custom_post' );
                  $role->add_cap( 'delete_private_custom_post' );
                  $role->add_cap( 'delete_published_custom_post' );

     }
}

我希望这可以帮助你,如果需要更多的帮助,请访问。

https://codex.wordpress.org/Function_Reference/register_post_type

and

https://codex.wordpress.org/Roles_and_Capabilities


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接