Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress Rest API - add user capability

Is there any way to add a capability to user using the Rest API?

I am creating the user this way:

$.ajax( {
    url: Slug_API_Settings.root + ‘wp/v2/users/’,
    method: ‘POST’,
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( ‘X-WP-Nonce’, Slug_API_Settings.nonce );
    },
    data:{
        email: ‘[email protected]’,
        username: ‘someone’,
        password: Math.random().toString(36).substring(7)
    }
    })
    .done( function ( response ) {
        console.log( response );
     })

Then I need to assign the capability to new user. Does anyone have a example of that?

Thanks very much!

like image 864
Marrone Avatar asked Feb 15 '26 21:02

Marrone


1 Answers

You can add the user role and capability by the WordPress REST API to the new users as per below code:

$.ajax( {
url: Slug_API_Settings.root + ‘wp/v2/users/’,
method: ‘POST’,
beforeSend: function ( xhr ) {
    xhr.setRequestHeader( ‘X-WP-Nonce’, Slug_API_Settings.nonce );
},
data:{
    email: ‘[email protected]’,
    username: ‘someone’,
    password: Math.random().toString(36).substring(7),
    roles: ‘contributor’
}
})
.done( function ( response ) {
    console.log( response );
 })

Roles conotributor have the capabilities like delete_posts, edit_posts and read you can also assign users to extra capabilities using extra_capabilities parameter.

You can also refer the WordPress API Official Docs Here

Please also refer the Roles and Capabilities Here.

like image 50
Ajay Ghaghretiya Avatar answered Feb 17 '26 13:02

Ajay Ghaghretiya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!