## Google Analytics Opt-Out Function Using wp_head + Remove Link When Clicked

Question

The aim / goal here is to be allow the visitor to turn ON Google Analytics as opposed to turning it OFF. In other words; it should be OFF by default with the option to turn it on.

If turned on, the cookie stays active until the year 2100 or until the user him or herself removes the cookie from the browser.

The code I have does the opposite (turns the tracking OFF) and I’ve done some changes to the code in the hope of reversing it myself, but I don’t know how to make it inactive by default, allowing the user / visitor to turn it ON by choice.

I’m hoping for some insight / help on how to reverse this code and in the process, help others looking to accomplish the same.

The code I have might be incorrect or outdated and if so, please feel free to correct it. While reversing the code is one thing, the other is removing the DIV-tag (hooked into wp_head) once the cookie is set, making it “display: none” and bringing it back if the cookie does not exist.

I found this on the official GA site, but I’m not sure how to apply it so that it “runs on a global level, affecting the entire site”, but more importantly, runs before the opt-in script.

window['ga-disable-UA-XXXXXX-Y'] = true;


This is the code that needs to be reversed (I’ve tried various versions without success):

add_action( 'wp_head', 'ga_opt_in', 1 );
function ga_opt_in(){   ?>

<script>
var gaProperty = 'UA-XXX-X';
var activateStr = 'ga-activate-' + gaProperty;
if (document.cookie.indexOf(activatetr + '=true') > -1) {
window[activateStr] = true;
}
function GAoptIn() {
document.cookie = activateStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
window[activateStr] = true;
}
</script>

<div class="ga-opt-in-link"><a href="javascript:GAoptIn()">Click here to turn Google Analytics Tracking ON</a></div>

<?php
}

0
2 years 2020-08-07T01:10:43-05:00 0 Answers 51 views 0