0

A third-party plugin adds the capability 'edit_booked_appointments'. I'd like to assign this capability to the already existing user role 'editor'. I created the following function in my child theme:

function add_booking_role_to_editor() {
    $role = get_role( 'editor' ); 
    $role->add_cap( 'edit_booked_appointments', true ); 
} 
add_action( 'init', 'add_booking_role_to_editor');

As far as I understand the whole topic, user roles get written to the database so there is no need to hook this function into the 'init' action. What would be the correct way to do this? Is there a way to fire this once, after the corresponding plugin has been activated? I tried it with the action 'plugins_loaded' but that did not work at all.

1
  • Perhaps this helps you out answer – Charles Jan 19 '20 at 3:03
1

The best place to add this would be in the plugin's activation hook. You can either call the dynamic activate_{$plugin} hook, or better yet use the provided register_activation_hook method.

Using your code example above - something like this would be what you're looking for:

register_activation_hook( __FILE__, function() {
    $role = get_role( 'editor' ); 
    $role->add_cap( 'edit_booked_appointments', true );
} );

It's also important to clean up after your plugin deactivates by registering a deactivation hook to clean up any DB changes you've made:

register_deactivation_hook( __FILE__, function() {
    $role = get_role( 'editor' ); 
    $role->remove_cap( 'edit_booked_appointments', true );
} );

Note: These code examples are being used in the main plugin file. If you're using it outside of that context, you'll need to provide the main plugin file instead of the magic __FILE__.

1
  • Thank you very much, that's exactly what I was looking for! – jexyon Jan 19 '20 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.