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.
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.
Share Improve this question asked Jan 19, 2020 at 0:17 jexyonjexyon 31 bronze badge 1- Perhaps this helps you out answer – Charles Commented Jan 19, 2020 at 3:03
1 Answer
Reset to default 1The 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__
.