2

I'm looking to create a custom plugin that will check for a specific cookie from the user, and if not found, redirect them to an authorization page where they can enter a code to access the site. This needs to happen across the entire site, including the login and register pages (don't ask, client specifications). I intend to do this by registering a function to the earliest WordPress hook that a) loads every single time a page is accessed, regardless of content, b) runs for every single page of the site, admin side included, and c) is called LATE enough that it has access to user data (we don't want to run this validation for the admin account). What is the earliest, always loaded, WordPress hook that I could use?

I've checked through WordPress's documentation and found a list of all hooks that are called on page load, but it doesn' specify which of them are ALWAYS called versus called for specific content (ie, does registered_taxonomy run on pages not associated with a taxonomy?).

My own best guess would be the init hook, but I'm not 100% positive. I'm also not sure if that would too early in the sequence of hooks to redirect to another page.

Alternatively, if there's a better way to handle this than WordPress hooks, I'm all ears!

1 Answer 1

6

registered_taxonomy is not available to normal plugins, only to must-use plugins. The first hook available to normal plugins is plugins_loaded. Although, the current user isn't set at this point, so there's no reason to hook this early.

set_current_user fires on every page - even if not logged in - immediately after the current user is set. See here. The function that calls the hook is "pluggable" though, so if a plugin does decide to override that function, it's possible that it won't fire that hook. That seems unlikely to me, so I do use this hook to use user data.

There are a couple other hooks fired besides set_current_user - unload_textdomain, load_textdomain, and after_setup_theme - that fire on every page. I suppose you could use those if you really wanted to.

If it were me, I'd use set_current_user. If you want to be extra careful, use init. init is early enough that you can still safely redirect.

As an aside, I'd recommend using the Query Monitor plugin. I've found it indispensable for WordPress development.

1
  • query-monitor is one very good plugin indeed. I tested it with rips and found 0 errors.
    – prosti
    Feb 5, 2017 at 17:46

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.