Ready to get started?Download WordPress


[resolved] Getting user info at wp_login hook? (3 posts)

  1. misterbrandt
    Posted 7 years ago #

    I am working on a plugin that, when a user successfully logs in to WP, checks that user's capabilities (using the current_user_can function) and conditionally sets a login cookie for ZenPhoto, which is installed side-by-side with WP.

    I am using the wp_login hook, which is the last hook I can use before the user is redirected and the admin_header stuff starts getting written (i.e. by then it's too late to set a cookie).

    But current_user_can wasn't returning the expected value, so I tried to check on the user by var_dump'ing the value returned by wp_get_current_user. But this function returns basically an empty user object even when the user should be successfully logged in:
    object(WP_User)#87 (6) {
    array(0) {
    array(0) {
    array(0) {

    However, if I reload wp-login.php after I log in, the same function returns a full-fledged user with all roles and everything in place.

    So, I guess the question is: what can I do from the wp_login hook to get the user info populated, so that I can use current_user_can? (Or, should I be trying to set this cookie at a different/better hook anyway??)

    Thanks for any insights. Oh, and I know how easy it would be to hack wp-login.php, but my goal is to keep this hack-free.

  2. VoodooLogic
    Posted 7 years ago #

    Hmmm. If you have the user login name by the time you're firing your plugin, could you use the $wpdb class to query wp_users and wp_usermeta to retrieve the information yourself?

    All the best,


  3. misterbrandt
    Posted 7 years ago #

    Voodoo - thanks for prodding me in the direction or doing it from scratct, rather than trying to figure out which global variables weren't available yet, and tracking those dependencies though everything.

    In the end, I was able to use get_userdatabylogin() to get a copy of the user object, and then I wrote a custom version of current_user_can() that uses get_option() to pull the roles and capabilities out of the db directly. For anyone else's future reference, this is how I did it:

    function elbe_zp_login( $user_login ) {
    $user = get_userdatabylogin($user_login);
    if (elbe_current_user_can('publish_posts', $user)) {
    } else {
    // echo "current user cannot publish posts...";
    } // end function

    function elbe_current_user_can($capability, $current_user) {
    $roles = get_option('wp_user_roles');
    $user_roles = $current_user->wp_capabilities;
    $user_roles = array_keys($user_roles, true);
    $role = $user_roles[0];
    $capabilities = $roles[$role]['capabilities'];
    if ( in_array( $capability, array_keys( $capabilities, true) ) ) {
    // check array keys of capabilities for match against requested capability
    return true;
    } // end function

Topic Closed

This topic has been closed to new replies.

About this Topic