Google Analytics opt-out header.php

Hello,

i need Google Analytics opt-out code in my header.php before . I`m working with Pro Child Theme. Is it enough to copy the header.php to Child Theme and put the Code into it?

Thanks for helping.

<script>
// Set to the same value as the web property used on the site
var gaProperty = 'UA-XXXX-Y';

// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
  window[disableStr] = true;
}

// Opt-out function
function gaOptout() {
  document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
  window[disableStr] = true;
}
</script>

Hi there,

You may also use the wp_head action hook to load the code in the head tag. You can do this by adding this code in the functions.php file of the child theme:

add_action( 'wp_head', 'add_head_script', 999 );

function add_head_script(){
?>
<script>
// Set to the same value as the web property used on the site
var gaProperty = 'UA-XXXX-Y';

// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
  window[disableStr] = true;
}

// Opt-out function
function gaOptout() {
  document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
  window[disableStr] = true;
}
</script>
<?php
}

Hope this helps.

Thank you :slight_smile: