Detecting SiteGround’s staging environment

Managed WordPress hosts reliably include a staging environment, and most hosts do a good job of providing both a means of detecting whether code is running on a staging environment and documentation explaining how that detection works.

WP Engine provides is_wpe() for detecting production and is_wpe_snapshot() for detecting their staging environment. (You’ll need to check for the existence of the functions in case your code runs elsewhere—in a local development environment, for example.)

Pantheon adds elements to PHP’s global $_ENV array, allowing you to check the value of $_ENV['PANTHEON_ENVIRONMENT'] for one of dev, test, or live depending on where the code is running.

SiteGround provides staging environments, but their documentation doesn’t describe how to detect the environment, and their support staff direct you to hire a developer if you’d like to do so.

One of the eccentricities of SiteGround’s staging environment is that it leaves your database untouched, so WordPress’s siteurl and home settings remain the same as in production. Instead, they modify the value of HTTP_HOST in Apache so that WordPress still thinks it’s running on the production URL.

Since we can’t trust HTTP_HOST, I detect the environment using DOCUMENT_ROOT instead:

// Check that the document root begins with the staging path.
if ( false !== strpos( $_SERVER['DOCUMENT_ROOT'], '/www/staging' ) ) {
	// Define a constant after detecting the staging environment.
	define( 'SITEGROUND_STAGING', true );
}

(Remember to swap in your own SiteGround username if you use the above snippet!)

Adding this code to wp-config.php creates a constant that I can check before doing things like deactivating plugins that shouldn’t be running on staging and activating others that should only run on staging. (It also allows me to fix an issue that prevents WooCommerce Subscriptions from detecting SiteGround’s staging environment.) I can rely on this code to continue working for so long as SiteGround abstains from changing the root path they use for staging environments, and I can safely run it in production so that it automatically copies to newly created staging servers.

WP Engine and Pantheon make it more straightforward to detect their staging environments, but it’s possible to do so on SiteGround as well—it’s just not documented or officially supported.

Leave a Reply

Your email address will not be published. Required fields are marked *