SOLVED – $wp_admin_bar and AJAX calls

That’s not how PHP requests work, you cannot set a variable in one request, then read it in another request. It isn’t like a Node or Python application where the program runs continuously in the background, every request is a blank slate.

So, to make it work, in the first request you need to put it somewhere that the second request can read from, for which there are several options:

  • Cookies
  • User meta
  • Options/Transients

As it’s a logged in user, and persisting across sessions would make sense, user meta seems the most logical choice, via update_user_meta and get_user_meta