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() {

And changed the roots_google_analytics() function like this:

function roots_google_analytics() { ?>
  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[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
    <?php else : ?>
      function ga() {
        console.log('GoogleAnalytics: ' + [];
    <?php endif; ?>
    ga('create','<?php echo GOOGLE_ANALYTICS_ID; ?>','auto');ga('send','pageview');

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?


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