When developing for a WordPress multisite, it is often necessary to load some custom code very early in the WordPress application’s loading sequence, e.g. to implement some custom domain mapping functionality. For multisite instances on VIP Go, we make it easy to load custom code as part of WordPress Core’s
Before discussing how, it’s important to note that
sunrise.php loads very early in WordPress, and most of its functions won’t be available. Further,
sunrise.php loads before
mu-plugins, any active plugins, and the active theme. As such, what can be done in
sunrise.php is limited, and largely confined to using pure PHP to set constants that override WordPress Core behavior.
To load additional code in
- Create a
vip-config/client-sunrise.phpfile in your site’s repository. On VIP Go, if the file is present, it will be loaded automatically (ref).
To achieve the same behavior on a local development environment:
As already mentioned, the purpose of
vip-config/client-sunrise.php is to execute PHP early in the WordPress cycle, before most of WordPress, including any theme or plugin code, loads. Typical uses for this file therefore share a few characteristics:
- The problem being solved requires early execution (e.g., for performance reasons or to override aspects of the request very early on). Code that can run later in execution should typically be written in the plugin or theme context and leverage WordPress’ Plugin API.
- The problem can be solved with (mostly) pure PHP.
- The problem being solved does not require database access or access to any persistent data, but often makes decisions or performs actions based on intrinsic characteristics of the request, such as the domain or URI. Because it executes on every single request handled by WordPress, make sure your use of
sunrise.phpdoes not introduce the kinds of performance penalties associated with queries or other expensive operations.
- The scope of the problem being solved is well understood and minimized. Code executed within
sunrise.phpis kind of like a sledgehammer, and can have far-reaching effects. Do as much as you can to limit the conditions under which the code executes (such as limiting it to only certain URLs or certain domains) to reduce the probability of unintended side-effects.