<?php if (wp_get_environment_type() === 'production' && isset($_COOKIE['pine-cookie-law-marketing']) && $_COOKIE['pine-cookie-law-marketing'] === 'accepted') : ?>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-5KW7WNP3TW"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-5KW7WNP3TW');
</script>
<?php endif; ?>
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:
Copy
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: