Detect and Set the Current Environment in WordPress

WordPressPosted on

1 min read

Detecting the current environment is a helpful feature. For example, we – usually – only want to run our analytics scripts only on production and not on staging or development.

Using the wp_get_environment_type() function (from WordPress 5.5) we can get the WP_ENVIRONMENT_TYPE constant value. If the constant doesn’t have a value the function will return “production”.

It can has four values: “production”, “local”, “development”, “staging”.

To set a value explicitly, go to your site’s wp-config.php and add the declaration:


define('WP_ENVIRONMENT_TYPE', 'staging');

For a real-life example, check out the following code where we only load the gtag.js if the site is on production and the related cookie is accepted:


<?php if (wp_get_environment_type() === 'production' && isset($_COOKIE['pine-cookie-law-marketing']) && $_COOKIE['pine-cookie-law-marketing'] === 'accepted') : ?>
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-xxxxxxxx-x"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-xxxxxxxx-x');
    </script>
<?php endif; ?>

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in WordPress category