1

Detect and Set the Current Environment in WordPress

 2 years ago
source link: https://pineco.de/snippets/detect-and-set-the-current-environment-in-wordpress/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Detect and Set the Current Environment in WordPress

We use cookies for commenting and analytics. For more details, please visit our privacy page.

Ugrás a tartalomhoz

Home Snippets WordPress Detect and Set the Current Environment in WordPress

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!

To see and write comments, you must allow the related (Disqus) cookies. For more information, please visit our privacy policy page.

Need a reliable, small web developer team? Try us! We develop with Laravel and Vue.js.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK