For all logged in visitors of my WordPress website I would like to set 2 cookies based on their user ID - so that I can use their user IDs in WordPress-unrelated PHP scripts at the same domain.

In one cookie I would like to store the user ID.

In the other cookie I'd like to store a md5 hash of the user ID and a secret word - so that I can verify in my PHP scripts, that the first cookie hasn't been faked.

Here is my code:

    $year = time() + 60 * 60 * 24 * 30 * 12;
    $auth = md5(join('_', array($user->ID, 'my_secret')));

    setcookie('visitor_id', $user->ID, $year, '/', '.example.com');
    setcookie('visitor_auth', $auth, $year, '/', '.example.com');

Please advise me, where to put this code in my plugin?

I have looked at the wp_set_auth_cookie, but I don't see how it could be used for my purpose. It seems to be a function to set some WordPress internal cookies, but not my custom cookies.

Or should I mayber put the above code into init hook? How can I find the user ID in there?

1 Answer 1


Nevermind, I've figured it out:

            function init() {
                    $user = wp_get_current_user(); 
                    if (!$user instanceof WP_User) 

                    $year = time() + 60 * 60 * 24 * 30 * 12;
                    $auth = md5(join('_', array($user->ID, "my secret")));

                    setcookie('visitor_id', $user->ID, $year, '/');
                    setcookie('visitor_auth', $auth, $year, '/');

            add_action('init', 'init');

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.