The active theme’s functions.php
is the first theme file loaded, in the file wp-settings.php
. All other theme files are loaded depending on the context of the request, which happens very late in the load process, after the user is authenticated, the request is parsed, and the query runs. Templates are for display, nothing belongs in a template that’s not related to front end display.
Most of the authentication stuff happens in pluggable.php
, which allows you to override the authentication functions. This is probably where you want to be looking if you want to customize the authentication process. The function wp_get_current_user
is triggered from the wp
class to kick off the process. There are also a few actions that are triggered in this process that let you run your own code and short-circuit the process, and are a much simpler and safer way to do your own auth stuff than fully overriding pluggable functions.
I suggest familiarizing yourself with the Action Reference to see the order in which things happen in the load process. Almost everything you do in WordPress will be hooked to an action to run at a specific time. I also suggest putting your code in a plugin or must-use plugin if you want it to be present regardless of selected theme.
As for the bonus question- I can’t think of one off the top of my head, maybe I will think of something later…