If you’ve ever worked on a project when you need to work with WordPress authentication cookies, then you’ve likely stumbled across the wp_set_auth_cookie function. In short, this function:

Sets the authentication cookies based User ID.

And when you use this function, you’re essentially creating a cookie that’s used to authenticate the user to log into WordPress.

WordPress User Caches

But if you’re looking to authenticate a user with WordPress programmatically, then there are a few extra steps required to do it properly especially if you’re working with caching plugins.

And that’s where WordPress user caches come into play.

WordPress User Caches

Aside from simply creating an authentication cookie, it’s important to make sure that you’re doing the following:

  • clear the user caches,
  • get rid of authentication cookies,
  • set a current user,
  • set the authentication cookie,
  • update the user caches.

It sounds like a complicated solution, right? The nice thing is that there are a handful of functions (linked above) that make this really easy.

The important thing to remember is that you need an instance of WP_User in order to do all of this. How you retrieve an instance of the user will depend on the functionality of your plugin.

That is, perhaps you’re able to retrieve a reference for a user given a username:

Or maybe you have an email address that you can use:

Whatever the case, the following steps must have a user if you’re to do this properly. So with that said, here’s how the code may look:

And that’s it! So here’s the description of what each function does:

  • clean_user_cache. This will remove all of the cached users’ information.
  • wp_clear_auth_cookie. When a user is authenticated with WordPress, there is a cookie that’s stored. This will clear that authentication cookie.
  • wp_set_current_user. Given an instance of WP_User, tell WordPress to mark this user (permitting s/he exists in the database)
  • wp_set_auth_cookie. This will create the cookie used for authentication for the user that was just set in the previous function.
  • update_user_caches. Finally, this will update the user caches with the information with the new years.

When it comes to working with WordPress user caching, authentication, and moving forward with programmatically authenticating users, these are the functions that should be used.


    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.