Add_action wp_authenticate or wp_login

I have a site where I want to update user info at login. This is important because the way a user interacts with the site is determined by information held in a CRM.

When a user logs in, I grab this info in a function that does an API call to the CRM. I then write the info to custom fields in the user profile and also update the user’s role.

I initially wrote the code using the wp_login hook. It worked in my dev environment but not the when I tried it in staging with the S2 plugin installed. I read here – S2member login wp-admin – that S2 overrides wp_login and that I should use wp_authenticate. I refactored the code for wp_authenticate and it tested good in dev, but again fails once it is in a site with S2.

Any Ideas of what I am missing? Is there another way to affect the user during the logon process?

function maximizer_login( $username ){
    error_log ('Max Login Hook');
    $user = get_user_by('login', $username);
    if ($user != NULL) {
        if( $user->has_cap( 'administrator') || $user->has_cap( 'editor')) {
        } else {
            if ( isset( $user->roles ) && is_array( $user->roles ) ) {
	            $userstring = "user_".$user->id;
                $userEmail = $user->user_email ;  
	       error_log ("Max user ". $userstring . " email is: ". $userEmail );
                $maxUserRole = get_maxi_user("$userEmail");
                if ($maxUserRole != NULL) {
                    $user->set_role( $maxUserRole['userrole'] );
                    update_field('company_name', $maxUserRole['businessname'], $userstring);   
                    update_field('company_id', $maxUserRole['businessid'], $userstring);	      
                } 
            } 
        }
    }
    return $username;
 }
add_action( 'wp_authenticate', 'maximizer_login' );

Just set a 5 sec delay at “wp_authenticate” (I use wp_cron), this way s2M will set what is need, and your code will runs after it, thus you will have the updated info, and will edit it later than s2M `so it will not be overwrited).

I appreciate the suggestion, but using a delay will not work in my case.

  • First, it does not seem that the function is being called at all. error_log (‘Max Login Hook’); is not sending the text to the error log.

  • Second, I need to adjust the member level before s2M does anything so I can set the user role to the proper state. When a user logs in the will see different content on the page dependent on their role.

A bit more investigation and I am able to do it. the file was not properly included when I moved it from my test system.

Thanks

1 Like