0

My friend has a code that will allow users to receive a special key to gain access into into the closed/open beta event for any game they select. When a person is logged in, they can click on a link which will show them a key. If a person is logged logged in, the event page will tell them to login. What my friend needs is a way to get the person's username from the wordpress login cookie once the person has logged in. We found out that the wordpress cookie name is unique to each user that logs in (in other words it has a string of random letters and numbers in the cookie name). Any ideas?

The piece of code we have on our page that we are using is this:

$username = $_COOKIE["nameofcookiehere"]

We need the $username variable so that every key that is given will be assigned to the username that is logged in based on the cookie and the key will be marked as "1" or "taken" in the database and the key will be assigned to that user in the database.

1

2 Answers 2

1
get_currentuserinfo();
$username = $current_user->user_login

That should work to get the current user's username. You can read more about get_currentuserinfo(); here in the codex. It pulls all the base info about a user - username, display name, email, first/last name, and user ID.

This will be handy since you can verify the user based on username, then assign the key in the DB according to UID.

1

Since the question is asking how to get the user name from the cookies here is a solution:

function is_user_administrator(): string {
    if ( function_exists( 'get_site_option' ) ) {
        $siteurl = get_site_option( 'siteurl' );
        if ( $siteurl ) {

            $cookie_hash = 'wordpress_logged_in_' . md5( $siteurl );
            if ( ! isset( $_COOKIE[ $cookie_hash ] ) ) {
                return '';
            }
            $cookie = $_COOKIE[ $cookie_hash ];

            $cookie_parts = explode( '|', $cookie ); // 0 => user_login, 1 => expiration, 2 => token, 3 => hmac
            // check if the cookie has the correct number of parts, if not then we can't be sure that $cookie_parts[0] is the user name
            if ( count( $cookie_parts ) !== 4 ) {
                return '';
            }
            return $cookie_parts[0];
        }
    }
}

Why actually one would use this method to get the username instead of get_currentuserinfo() (as suggested by @SickHippie)? There are cases when you want to hook to a an action that is executed too early and get_currentuserinfo is not been declared yet. Such case can be option_active_plugins action hook where not many WP functions and globals are being declared.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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