Detect and Set the Current Environment local, product phathaiantoan.com.vn (ok)

https://pineco.de/snippets/detect-and-set-the-current-environment-in-wordpress/

C:\xampp82\htdocs\wp2\wp-config.php

define('WP_ENVIRONMENT_TYPE', 'staging');

C:\xampp82\htdocs\wp2\wp-content\themes\falcha-news-child\functions.php

if(wp_get_environment_type() != 'staging') :
add_filter( 'amp_post_template_analytics', 'xyz_amp_add_custom_analytics' );
function xyz_amp_add_custom_analytics( $analytics ) {
  if ( ! is_array( $analytics ) ) {
    $analytics = array();
  }
  // https://developers.google.com/analytics/devguides/collection/amp-analytics/
  $analytics['xyz-googleanalytics'] = array(
    'type' => 'gtag',
    'attributes' => array(
      'data-credentials' => 'include',
    ),
    'config_data' => array(
      'vars' => array(
        'gtag_id' => 'G-5KW7WNP3TW',
        'config' => array(
          'G-5KW7WNP3TW' => array(
            'groups' => 'default',
          ),
        ),
      )
    ),
  );
  return $analytics;
};
endif;

C:\xampp82\htdocs\wp2\wp-content\themes\falcha-news-child\header.php

<?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:

Copy
<?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; ?>

Last updated