Here's how you can use Free Cookie Consent to integrate Google Consent Mode V2.
In our example here, we assume that you already have implemented the Cookie Consent solution on your websites. If not, create it.
In this example, we'll use a website powered by WordPress. If your website uses a different CMS, the steps remain the same:
- Create the gtag function with the default consent states as denied
- Load the Google Analytics/Tag Manager script
- Update the consent state based on user acceptance using Cookie Consent callbacks
Steps
-
Create the necessary gtag function with the default consent states as denied:
The code should be:
<script> window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('consent', 'default', { 'ad_storage': 'denied', 'ad_user_data': 'denied', 'ad_personalization': 'denied', 'analytics_storage': 'denied' }); </script>
-
Add the code before the start of the existing Cookie Consent code:
-
Load the Google Analytics / Google Tag Manager script. If you already tagged the Google script for Cookie Consent, remove the data-cookie-consent parameter:
The code should be something like this (replace
TAG_ID
with your own ID):<script async src="https://www.googletagmanager.com/gtag/js?id=
TAG_ID
"></script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'TAG_ID
'); </script> -
Add the code below the first code from Step 1:
-
Now let's adapt your Cookie Consent config code. In our example here, we've formatted the config code (in JSON format) for better readability.
The config code is the code inside the "
cookieconsent.run({ })
" function.Add a comma next to the last line from the config code in order to add new parameters:
-
Add 2 new parameters in the Cookie Consent config code:
callbacks
andcallbacks_force
. The callbacks functionality is necessary to update the consent states based on user acceptance (after users click I Agree):The code should be:
"callbacks": { "scripts_specific_loaded": (level) => { switch(level) { case 'targeting': gtag('consent', 'update', { 'ad_storage': 'granted', 'ad_user_data': 'granted', 'ad_personalization': 'granted', 'analytics_storage': 'granted' }); break; } } }, "callbacks_force": true
-
Add the callbacks code inside the Cookie Consent config code:
-
Save your changes.
-
Your Cookie Consent notice banner now integrates Google Consent Mode V2: