Hi
My registered users get the Subscriber role. If they fill in their "New store" form they create a new post in the Stores custom post (author=user) so I'd like to change the user role to "Shop manager" when saving the form. Also, the opposite, if the user decides to delete their store post I'd like the role to go back to Subscriber. Is there a way to do this ?
thanks
Regards
Nicola
Please check the following code(please update the form ID in the first function):
function change_user_role_on_save($post_id, $form_data)
{
// Specify the form ID
if ($form_data["id"] == 573) {
$user = wp_get_current_user();
if (in_array("subscriber", (array) $user->roles)) {
// Remove role
$user->remove_role("subscriber");
// Add role
$user->set_role("shop_manager");
}
}
}
add_action("cred_save_data", "change_user_role_on_save", 10, 2);
function check_and_update_user_role_on_delete($post_id) {
// Check if the deleted post is of the 'store' custom post type
if (get_post_type($post_id) === 'store') {
// Get the user who deleted the post
$current_user = wp_get_current_user();
// Check if the user is a 'shop_manager'
if (in_array('shop_manager', $current_user->roles)) {
// Count the number of 'store' posts published by the user
$store_posts_count = count_user_posts($current_user->ID, 'store');
// If the user has no other 'store' posts published, change their role to 'subscriber'
if ($store_posts_count <= 1) {
$user_id = $current_user->ID;
// Remove the 'shop_manager' role
$current_user->remove_role('shop_manager');
// Add the 'subscriber' role
$current_user->add_role('subscriber');
}
}
}
}
add_action('before_delete_post', 'check_and_update_user_role_on_delete');
I created two functions, one that will be triggered when the form is saved and check if the user role is subscriber, if so, it changes it to shop_manager.
The second function runs if a post from the CPT store gets removed and that user has no other published store attached to them. In that case the user gets its role change back to subscribe.
Please note: the code provided is to be used as an informational one. remember that custom coding is out of the scope of our support so we can't create, debug or modify code for you and it's your responsibility to maintain it. we hope the one we used as an example could point you in the right direction.
Hello Mateus,
thank you very much for your snippet, I am not a PHP expert. The first function works fine, but the second function should not be triggered when saving the Add store form, but when the user wants to delete the store. I have a simple view listing all stores belonging to the current user with the classic VIEW | EDIT | DELETE links. The Delete links is the usual [cred-delete-post]. Here is where the check_and_update_user_role_on_delete in your snippet should be triggered. Is there a way to trigger the second half of your snippet when the DELETE link is selected ?
thanks
Regards
Nicola