1

User 19 is a WP Admin.

$user = new WP_user( 19 );
$user->add_role( 'custom_role' );

The above code works and adds the custom_role role.

However, when I run the same code on the personal_options_update and edit_user_profile_update hook it does not.

I have added a checkbox to the user profile page. The function called from both the above hooks then...

if( user_can( $user_id, 'administrator' ) ) {
    $user = get_user_by( 'id', $user_id );      
    if( ! empty( $_POST['my_checkbox'] ) )  {

        update_user_meta( $user_id, 'my_checkbox', true );
        $user->add_cap( 'one_cap' );
        $user->add_cap( 'two_cap' );
        $user->add_role( 'custom_role' );

    }
}

one_cap and two_cap are both set correctly for the user, but no sign of custom_role and nothing written to the debug log.

What could be the cause of this?

1 Answer 1

1

use the profile_update hook and in the hooked function, run this check to make sure that it's adding the previous data to the users profile on update too.

if ( $update ){
        do_action('profile_update', $user_id, $old_user_data);
}else{
        do_action('user_register', $user_id);
}
return $user_id;

This answer can help you understand it more: WordPress edit_user_profile_update update secondary role

2
  • 1
    Thank you! Makes perfect sense that I was hooking too early
    – Mike
    Commented Apr 20, 2016 at 8:28
  • you're welcome! voting up the answer helps me too! ;) Commented Apr 20, 2016 at 8:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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