Function Friday #24: check your environment before loading code

Function Friday #24

Every Friday, I’m sharing code snippets that I use to customize WordPress. Feedback/suggestions are always welcome! For more information, check out the first post in the series.


While it’s great to avoid cowboy coding by having both local and staging versions of your website, you shouldn’t indiscriminately load code on all three environments. The Google Analytics tracking script is one example of code you probably don’t want mirrored on your local and staging sites.

You can use the same theme/plugin files on different environments, you just have to check where you are before loading environment-specific content.

The code

// Check environment before loading code
if ( defined( 'WP_NOT_PRODUCTION' ) && WP_NOT_PRODUCTION ) {
    // Do not output
} else {
    // Output production-only code here
}

This code checks for a constant called WP_NOT_PRODUCTION. On any non-production installs, edit wp-config.php and add this to the file:

define( 'WP_NOT_PRODUCTION', TRUE );

You can define constants anywhere, but for this purpose I like to do it in wp-config.php, because it will change on each environment anyway to include different database details.

If your hosting company is WP Engine, they have a function for this exact purpose – is_wpe:

// Check environment before loading code
if ( function_exists( 'is_wpe' ) ) {
    if ( is_wpe() ) {
        // Output production-only code here
    }
}

This function returns true only on their production environment (so if you’re using their staging environment, this function has you covered as well). You do want to check whether the function exists before calling it, though, to avoid a fatal error on anything other than a WP Engine-hosted site.

Where does it go?

Define the constant in your wp-config.php file. Outputting the code can happen anywhere in your theme or plugin. More thoughts on code location are in the first Function Friday post.

Resources

Leave a Reply

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