Add Google Analytics after accepting cookies?

Hi there,

It’s still a bit unclear if it’s really necessary by law, but is it possible to somehow run the roots_google_analytics() function in scripts.php after cookies are accepted?

I’m using CookieCuttr to add a cookiebar at the top of my website and initialize the script at the top of my _main.js like this:

var Roots = {
  // All pages
  common: {
    init: function() {
      $.cookieCuttr();
    }
  }
};

And changed the roots_google_analytics() function like this:

function roots_google_analytics() { ?>
<script>
  if (jQuery.cookie('cc_cookie_accept') == "cc_cookie_accept") {
    // insert the code you do not want to run UNTIL cookies are accepted here
    console.log('cookies accepted');
    <?php if (WP_ENV === 'production') : ?>
      (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
      function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
      e=o.createElement(i);r=o.getElementsByTagName(i)[0];
      e.src='//www.google-analytics.com/analytics.js';
      r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
    <?php else : ?>
      function ga() {
        console.log('GoogleAnalytics: ' + [].slice.call(arguments));
      }
    <?php endif; ?>
    ga('create','<?php echo GOOGLE_ANALYTICS_ID; ?>','auto');ga('send','pageview');
  }
</script>

But it’s adding the Google Analytics script anyway, regardless if the cookies are accepted yet?
How should I reference the jQuery jQuery.cookie('cc_cookie_accept') parameter in the scripts.php file correctly?

Thanks!

Duh, I can check it directly in php of course :slight_smile:

if (GOOGLE_ANALYTICS_ID && (WP_ENV !== 'production' || !current_user_can('manage_options')) && isset($_COOKIE['cc_cookie_accept']) && $_COOKIE['cc_cookie_accept'] == 'cc_cookie_accept') {
  add_action('wp_footer', 'roots_google_analytics', 20);
}