Set cookie in Wordpress/PHP when user takes action, NOT during the init hook?

Viewed 20

So I've been reading that when working with wordpress one should avoid using PHP sessions (session_start).

I myself am using this method (very successfully) inside theme development (functions.php) but trying to clean it up to follow best practices. All of examples I've seen of cookies implemented with wordpress use php setcookie function during a wordpress hook, like init or wp.

So, on the one hand, I can understand that the reason for this is because the cookie needs to be set before headers are sent.

However, apparently this is not good practice (and it does not make sense in my situation, when I need to set a cookie on the php side only from inside a function call (after it receives an authentication OK from a 3rd party API), not in a webhook that will fire with every page load.

I must be missing something obvious but I'd love any input on how to correctly set a cookie upon a certain condition inside php... for example:

//Flow:

function load_current_user() {
   $auth_ok = /* cURL call that returns true */;
   if ($auth_ok == true) {
      // Set cookie to store user name and auth_flag = true;
      // This is the only time I want to set the SESSION cookie, not during init, wp, etc...
   }
}

Thank you kindly.

0 Answers
Related