8

I'm developing a shopping cart plugin, and planning to create a new user role for customers.

My question is how to create custom capabilities so that i can assign these custom capabilities to the new user role, this answer provided a way to create new capabilities, but it is just a new name for the original capabilities.

Can anyone explain how to create a brand new capability which controls some custom functions?

disinfor
  • 10,865
  • 2
  • 33
  • 44
Minqi
  • 79
  • 1
  • 1
  • 2
  • 1
    @maiorano84 Thanks, i've been search around for a while, couldn't find something addressing my exact requirement. – Minqi Jan 31 '13 at 04:02
  • http://wordpress.stackexchange.com/questions/35165/how-do-i-created-a-custom-capability – RRikesh Jan 31 '13 at 05:04
  • 7
    The irony of the "Let me just Google that for you" is that Google brought me here – IAmJulianAcosta Feb 19 '14 at 02:43
  • Hi. Did you figure this one out? I'm in kind of the same pickle. I want a capability to edit order status only in WooCommerce. – bronlund Mar 05 '18 at 14:35

2 Answers2

8

You should first understand that Wordpress user roles are simple as set of capabilities. That being said, since you said you are creating a plugin, I like to think you are no stranger to code and hence not afraid to code your solution rather than using another plugin for this.

This code should help you create a new user role and add custom capability to it.

<?php

// create a new user role

function wpeagles_example_role()
{
    add_role(
        'example_role',
        'example Role',
        [
            // list of capabilities for this role
            'read'         => true,
            'edit_posts'   => true,
            'upload_files' => true,
        ]
    );
}

// add the example_role
add_action('init', 'wpeagles_example_role');

To add a custom capability to this user role use the code below:

//adding custom capability
<?php
function wpeagles_example_role_caps()
{
    // gets the example_role role object
    $role = get_role('example_role');

    // add a custom capability 
    // you can remove the 'edit_others-post' and add something else (your     own custom capability) which you can use in your code login along with the current_user_can( $capability ) hook.
    $role->add_cap('edit_others_posts', true);
}

// add example_role capabilities, priority must be after the initial role     definition
add_action('init', 'wpeagles_example_role_caps', 11);

Futher reference: https://developer.wordpress.org/plugins/users/roles-and-capabilities/

0

You can create custom roles and capabilities by plugin. Two options available there by custom code or you can use existing plugin.

For Custom code: https://wordpress.stackexchange.com/questions/35165/how-do-i-create-a-custom-role-capability

Using existing plugin: User Roles and Capabilities

Community
  • 1
  • 1
solvease
  • 529
  • 2
  • 11