# Add Google Analytics after accepting cookies?

**URL:** https://discourse.roots.io/t/add-google-analytics-after-accepting-cookies/2306
**Category:** archived 🗄
**Created:** 2014-09-24T09:52:40Z
**Posts:** 2

## Post 1 by @Twansparant — 2014-09-24T09:52:40Z

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](http://cookiecuttr.com/) 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!

---

## Post 2 by @Twansparant — 2014-09-24T12:36:58Z

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);
}
```

---

## Post 3 by @ben — 2022-02-26T03:20:26Z


