Aleš Sýkora / November 28, 2023 / 10 comments

Free Cookie Consent in WordPress with Tag Manager Consent Mode

Post summary: This tutorial is created for all people who try to set up their EU cookie consent with WordPress website (and with Oxygen builder). I am using open source projects from Orest Bida – Send hype to this boy!! This tutorial will show how to prepare Cookie Consent with Google Analytics – with Google Consent Mode…

This tutorial is created for all people who try to set up their EU cookie consent with WordPress website (and with Oxygen builder). I am using open source projects from Orest Bida – Send hype to this boy!!

This tutorial will show how to prepare Cookie Consent with Google Analytics – with Google Consent Mode and with Meta (Facebook) Pixel and one scripts outside Google Tag Manager.

I will have functionality cookies enabled by default and everything else disabled.

I am not responsible for the correct settings with regard to GDPR and data protection. You must set this up according to the laws of your country and with the advice of your lawyer and data controller. Google Tag Manager Consent mode still use user agent, IP address and others.

Prerequisities:

  • Orest Bida Cookie Consent v 2.8.0 – get it here
  • Google Tag Manager with Google Analytics Code
  • Facebook Pixel Code
  • One Custom tracking Code

I am going to add the cookie consent banner code directly into WordPress. I will use the Advanced Scripts plugin to add the code and scripts. You can use other custom code plugins like code snippets or you can add the code directly to you WordPress website child template files. It depends only on your workflow.

Page head will be the place for initiating Google Consent mode and loading Google Tag Manager after that (on every page you want). You can enable or disable cookie storages simply by changing the ad_storage, personalization_storage etc. to granted/denied. This setting is same as default Google Consent Mode storage types in Google Tag Manager tag settings.

Google Consent Mode storage settings in Tag settings

Complete <head> code

Add this code immediately after opening <head> tag of your website. You can use the wp_head hook. Do not forget to change your xxx-xxxxxx GTM ID!

<!-- Google Consent Mode -->
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }

    gtag('consent', 'default', {
        'ad_storage': 'denied',
        'analytics_storage': 'denied',
        'functionality_storage': 'granted',
        'personalization_storage': 'denied',
        'security_storage': 'denied',
    });
</script>
<!-- End of Google Consent Mode -->

<!-- Google Tag Manager - Don't forget to change the xxx-xxxxxx to your GTM ID -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','xxx-xxxxxx');</script>
<!-- End Google Tag Manager -->

I am using Advanced scripts plugin for that:

Adding code to the head with Advanced scripts

This point is crucial. You need to configure the whole Cookie Consent banner and prepare the functions for changing consent mode status. I will show just some basic things which I set up. You can configure and customize you banner easily by official guide & Readme on github.

Include cookieconsent.js

You need to load the cookie consent banner script at very top of page. You can add it to the page head or page body. I prefer the page head to be loaded ASAP.

<script src="https://cdn.jsdelivr.net/gh/orestbida/[email protected]/dist/cookieconsent.js"></script>

With Advanced Scripts:

Including script to page head with advanced scripts in wordpress

If you looked at the documentation, you have already saw the settings and it meanings and options. For example, you can customize layout, position, transitions, language and more. Customization is in the gui_options: table.

This is how the GUI options table looks like (do not copy this code yet, this is just for explanation):

gui_options: {
                consent_modal: {
                    layout: 'cloud',               // box/cloud/bar
                    position: middle center',     // bottom/middle/top + left/right/center
                    transition: 'slide',           // zoom/slide
                    swap_buttons: false            // enable to invert buttons
                },
                settings_modal: {
                    layout: 'bar',                 // box/bar
                    // position: 'left',           // left/right
                    transition: 'slide'            // zoom/slide
                }
            },

            current_lang: 'en',
            autoclear_cookies: true,                   // default: false
            theme_css: 'https://cdn.jsdelivr.net/gh/orestbida/[email protected]/dist/cookieconsent.css',  // ? replace with a valid path
            page_scripts: false,                        // default: false

            mode: 'opt-in',                          // default: 'opt-in'; value: 'opt-in' or 'opt-out'
            // delay: 0,                               // default: 0
            auto_language: 'document',                      // default: null; could also be 'browser' or 'document'
            // autorun: true,                          // default: true
            // force_consent: false,                   // default: false
            // hide_from_bots: false,                  // default: false
            // remove_cookie_tables: false             // default: false
            // cookie_name: 'cc_cookie',               // default: 'cc_cookie'
            cookie_expiration: 182,                 // default: 182 (days)
            // cookie_necessary_only_expiration: 182   // default: disabled
            // cookie_domain: location.hostname,       // default: current domain
            // cookie_path: '/',                       // default: root
            // cookie_same_site: 'Lax',                // default: 'Lax'
            // use_rfc_cookie: false,                  // default: false
            // revision: 0,                            // default: 0

Next part of Cookie Consent code is onAccept and onChange functions. I modified the cookie consent with function which communicates with the consent settings in way, that if you accept some cookie category (onAccept) then consent for that category is allowed. When you change it afterwards it change the consents too (onChange).

I am working with this default status:

'ad_storage': 'denied',
'analytics_storage': 'denied',
'functionality_storage': 'granted',
'personalization_storage': 'denied',
'security_storage': 'denied',

If you don’t need all categories, then feel free to delete them from onAccept and onChange functions.

This is how the changing of consent status looks like: (do not copy this code yet, this is just for explanation):

onFirstAction: function (user_preferences, cookie) {
                    // callback triggered only once on the first accept/reject action
                },
    
                onAccept: function (cookie) {
                    if (cc.allowedCategory('analytics')) {
                        gtag('consent', 'update', {
                            'analytics_storage': 'granted'
                        });
                    }
                    if (cc.allowedCategory('advertising')) {
                        gtag('consent', 'update', {
                            'ad_storage': 'granted'
                        });
fbq('consent', 'grant');
                    }
                    if (cc.allowedCategory('personalization')) {
                        gtag('consent', 'update', {
                            'personalization_storage': 'granted',
                        });
                    }
                    if (cc.allowedCategory('security')) {
                        gtag('consent', 'update', {
                            'security_storage': 'granted'
                        });
                    }
                },
    
                onChange: function (cookie, changed_categories) {
                    // callback triggered when user changes preferences after consent has already been given
                   if (cc.allowedCategory('analytics')) {
                        gtag('consent', 'update', {
                            'analytics_storage': 'granted'
                        });
                    }
                    if (!cc.allowedCategory('analytics')) {
                        gtag('consent', 'update', {
                            'analytics_storage': 'denied'
                        });
                    }
                    if (cc.allowedCategory('advertising')) {
                        gtag('consent', 'update', {
                            'ad_storage': 'granted'
                        });
fbq('consent', 'grant');
                    }
                    if (!cc.allowedCategory('advertising')) {
                        gtag('consent', 'update', {
                            'ad_storage': 'denied'
                        });
fbq('consent', 'revoke');
                    }
                    if (cc.allowedCategory('personalization')) {
                        gtag('consent', 'update', {
                            'personalization_storage': 'granted',
                        });
                    }
                    if (!cc.allowedCategory('personalization')) {
                        gtag('consent', 'update', {
                            'personalization_storage': 'denied',
                        });
                    }
                    if (cc.allowedCategory('security')) {
                        gtag('consent', 'update', {
                            'security_storage': 'granted'
                        });
                    }
                    if (!cc.allowedCategory('security')) {
                        gtag('consent', 'update', {
                            'security_storage': 'denied'
                        });
                    }
                },

Last things in the setup are texts, cookie tables and translations. You can find how to edit the cookie tables in the Github readme. The translation is used automatically by page Language code. So if you are using en-US and for example de-DE you need to set the language name to be the same: ‘en-US’: and ‘de-DE’:.

You can find which language codes your web uses in HTML code in start of page:

Language Code

Don’t forget to add a link to contact page and to you privacy policy or cookie policy page. If you want to add custom link, you can add it normally with “<a href=””>Link text</a>” inside the translations.

This is how the translation and cookie tables can look like: (do not copy this code yet, this is just for explanation):

languages: {
                    'en-US': {
                        consent_modal: {
                            title: 'We use cookies!',
                            description: 'Hi, this website uses essential cookies to ensure its proper operation and tracking cookies to understand how you interact with it. The latter will be set only after consent. <button type="button" data-cc="c-settings" class="cc-link">Let me choose</button>',
                            primary_btn: {
                                text: 'Accept all',
                                role: 'accept_all'              // 'accept_selected' or 'accept_all'
                            },
                            secondary_btn: {
                                text: 'Reject all',
                                role: 'accept_necessary'        // 'settings' or 'accept_necessary'
                            }
                        },
                        settings_modal: {
                            title: 'Cookie preferences',
                            save_settings_btn: 'Save settings',
                            accept_all_btn: 'Accept all',
                            reject_all_btn: 'Reject all',
                            close_btn_label: 'Close',
                            cookie_table_headers: [
                                { col1: 'Name' },
                                { col2: 'Domain' },
                                { col3: 'Expiration' },
                                { col4: 'Description' }
                            ],
                            blocks: [
                                {
                                    title: 'Cookie usage ?',
                                    description: 'I use cookies to ensure the basic functionalities of the website and to enhance your online experience. You can choose for each category to opt-in/out whenever you want. For more details relative to cookies and other sensitive data, please read the full <a href="#" class="cc-link">privacy policy</a>.'
                                }, {
                                    title: 'Strictly necessary cookies',
                                    description: 'These cookies are essential for the proper functioning of my website. Without these cookies, the website would not work properly',
                                    toggle: {
                                        value: 'functionality',
                                        enabled: true,
                                        readonly: true          // cookie categories with readonly=true are all treated as "necessary cookies"
                                    }
                                }, {
                                    title: 'Performance and Analytics cookies',
                                    description: 'These cookies allow the website to remember the choices you have made in the past',
                                    toggle: {
                                        value: 'analytics',     // your cookie category
                                        enabled: false,
                                        readonly: false
                                    },
                                    cookie_table: [             // list of all expected cookies
                                        {
                                            col1: '^_ga',       // match all cookies starting with "_ga"
                                            col2: 'google.com',
                                            col3: '2 years',
                                            col4: 'description ...',
                                            is_regex: true
                                        },
                                        {
                                            col1: '_gid',
                                            col2: 'google.com',
                                            col3: '1 day',
                                            col4: 'description ...',
                                        }
                                    ]
                                }, {
                                    title: 'Advertisement and Targeting cookies',
                                    description: 'These cookies collect information about how you use the website, which pages you visited and which links you clicked on. All of the data is anonymized and cannot be used to identify you',
                                    toggle: {
                                        value: 'advertising',
                                        enabled: false,
                                        readonly: false
                                    }
                                }, {
                                    title: 'Personalization cookies',
                                    description: 'These cookies collect information about how you use the website, which pages you visited and which links you clicked on. All of the data is anonymized and cannot be used to identify you',
                                    toggle: {
                                        value: 'personalization',
                                        enabled: false,
                                        readonly: false
                                    }
                                }, {
                                    title: 'Security cookies',
                                    description: 'These cookies collect information about how you use the website, which pages you visited and which links you clicked on. All of the data is anonymized and cannot be used to identify you',
                                    toggle: {
                                        value: 'security',
                                        enabled: false,
                                        readonly: false
                                    }
                                }, {
                                    title: 'More information',
                                    description: 'For any queries in relation to our policy on cookies and your choices, please <a class="cc-link" href="#yourcontactpage">contact us</a>.',
                                }
                            ]
                        }
                    },
                    'cs-CZ': {
                        consent_modal: {
                            title: 'Po našich sušenkách se vám zuby nezkazí!',
                            description: 'Dobrý den, na našem webu používáme cookies, abychom zjistili kolik lidí nám sem chodí a jaké služby je zajímají. Tyto soubory můžeme používat pouze s vaším souhlasem. <button type="button" data-cc="c-settings" class="cc-link">Vyberte si na co máte chuť</button>',
                            primary_btn: {
                                text: 'Sníst všechny',
                                role: 'accept_all'              // 'accept_selected' or 'accept_all'
                            },
                            secondary_btn: {
                                text: 'Držet hladovku',
                                role: 'accept_necessary'        // 'settings' or 'accept_necessary'
                            }
                        },
                        settings_modal: {
                            title: 'Vyberte si na co máte chuť',
                            save_settings_btn: 'Uložit nastavení',
                            accept_all_btn: 'Sníst všechny',
                            reject_all_btn: 'Držet hladovku',
                            close_btn_label: 'Zavřít',
                            cookie_table_headers: [
                                { col1: 'Name' },
                                { col2: 'Domain' },
                                { col3: 'Expiration' },
                                { col4: 'Description' }
                            ],
                            blocks: [
                                {
                                    title: 'Používáme tyto cookies ?',
                                    description: 'I use cookies to ensure the basic functionalities of the website and to enhance your online experience. You can choose for each category to opt-in/out whenever you want. For more details relative to cookies and other sensitive data, please read the full <a href="#" class="cc-link">privacy policy</a>.'
                                }, {
                                    title: 'Strictly necessary cookies',
                                    description: 'These cookies are essential for the proper functioning of my website. Without these cookies, the website would not work properly',
                                    toggle: {
                                        value: 'functionality',
                                        enabled: true,
                                        readonly: true          // cookie categories with readonly=true are all treated as "necessary cookies"
                                    }
                                }, {
                                    title: 'Performance and Analytics cookies',
                                    description: 'These cookies allow the website to remember the choices you have made in the past',
                                    toggle: {
                                        value: 'analytics',     // your cookie category
                                        enabled: false,
                                        readonly: false
                                    },
                                    cookie_table: [             // list of all expected cookies
                                        {
                                            col1: '^_ga',       // match all cookies starting with "_ga"
                                            col2: 'google.com',
                                            col3: '2 years',
                                            col4: 'description ...',
                                            is_regex: true
                                        },
                                        {
                                            col1: '_gid',
                                            col2: 'google.com',
                                            col3: '1 day',
                                            col4: 'description ...',
                                        }
                                    ]
                                }, {
                                    title: 'Advertisement and Targeting cookies',
                                    description: 'These cookies collect information about how you use the website, which pages you visited and which links you clicked on. All of the data is anonymized and cannot be used to identify you',
                                    toggle: {
                                        value: 'advertising',
                                        enabled: false,
                                        readonly: false
                                    }
                                }, {
                                    title: 'Personalization cookies',
                                    description: 'These cookies collect information about how you use the website, which pages you visited and which links you clicked on. All of the data is anonymized and cannot be used to identify you',
                                    toggle: {
                                        value: 'personalization',
                                        enabled: false,
                                        readonly: false
                                    }
                                }, {
                                    title: 'Security cookies',
                                    description: 'These cookies collect information about how you use the website, which pages you visited and which links you clicked on. All of the data is anonymized and cannot be used to identify you',
                                    toggle: {
                                        value: 'security',
                                        enabled: false,
                                        readonly: false
                                    }
                                }, {
                                    title: 'More information',
                                    description: 'For any queries in relation to our policy on cookies and your choices, please <a class="cc-link" href="#yourcontactpage">contact us</a>.',
                                }
                            ]
                        }
                    }
                }
            });
        });

Add the Complete script to the page <body>

Now you know how the Cookie Consent by Orest Bida works, so your last action – add the omplete Cookie Consent script into Advanced scripts file. Use the wp_body_open hook and do not forget to add your GTM ID at the end of file. You can delete the parts of consent you do not need.

For example, you do not use personalization cookies? Just delete the onAccept and onChange functions for them, and also, delete the translation.

<script>
    window.addEventListener('load', function () {

        // obtain plugin
        var cc = initCookieConsent();

        // run plugin with your configuration
        cc.run({

            gui_options: {
                consent_modal: {
                    layout: 'cloud',               // box/cloud/bar
                    position: 'middle center',     // bottom/middle/top + left/right/center
                    transition: 'slide',           // zoom/slide
                    swap_buttons: true            // enable to invert buttons
                },
                settings_modal: {
                    layout: 'bar',                 // box/bar
                    position: 'left',           // left/right
                    transition: 'slide'            // zoom/slide
                }
            },

            current_lang: 'cs',
            autoclear_cookies: true,                   // default: false
            theme_css: 'https://cdn.jsdelivr.net/gh/orestbida/[email protected]/dist/cookieconsent.css',  // ? replace with a valid path
            page_scripts: false,                        // default: false

            mode: 'opt-in',                          // default: 'opt-in'; value: 'opt-in' or 'opt-out'
            // delay: 0,                               // default: 0
            auto_language: 'document',                      // default: null; could also be 'browser' or 'document'
            // autorun: true,                          // default: true
            // force_consent: false,                   // default: false
            // hide_from_bots: false,                  // default: false
            // remove_cookie_tables: false             // default: false
            // cookie_name: 'cc_cookie',               // default: 'cc_cookie'
            cookie_expiration: 182,                 // default: 182 (days)
            // cookie_necessary_only_expiration: 182   // default: disabled
            // cookie_domain: location.hostname,       // default: current domain
            // cookie_path: '/',                       // default: root
            // cookie_same_site: 'Lax',                // default: 'Lax'
            // use_rfc_cookie: false,                  // default: false
            // revision: 0,                            // default: 0


  onFirstAction: function (user_preferences, cookie) {
                    // callback triggered only once on the first accept/reject action
                },
    
                onAccept: function (cookie) {
                    if (cc.allowedCategory('analytics')) {
                        gtag('consent', 'update', {
                            'analytics_storage': 'granted'
                        });
                    }
                    if (cc.allowedCategory('advertising')) {
                        gtag('consent', 'update', {
                            'ad_storage': 'granted'
                        });
fbq('consent', 'grant');
                    }
                    if (cc.allowedCategory('personalization')) {
                        gtag('consent', 'update', {
                            'personalization_storage': 'granted',
                        });
                    }
                    if (cc.allowedCategory('security')) {
                        gtag('consent', 'update', {
                            'security_storage': 'granted'
                        });
                    }
                },
    
                onChange: function (cookie, changed_categories) {
                    // callback triggered when user changes preferences after consent has already been given
                   if (cc.allowedCategory('analytics')) {
                        gtag('consent', 'update', {
                            'analytics_storage': 'granted'
                        });
                    }
                    if (!cc.allowedCategory('analytics')) {
                        gtag('consent', 'update', {
                            'analytics_storage': 'denied'
                        });
                    }
                    if (cc.allowedCategory('advertising')) {
                        gtag('consent', 'update', {
                            'ad_storage': 'granted'
                        });
fbq('consent', 'grant');
                    }
                    if (!cc.allowedCategory('advertising')) {
                        gtag('consent', 'update', {
                            'ad_storage': 'denied'
                        });
fbq('consent', 'revoke');
                    }
                    if (cc.allowedCategory('personalization')) {
                        gtag('consent', 'update', {
                            'personalization_storage': 'granted',
                        });
                    }
                    if (!cc.allowedCategory('personalization')) {
                        gtag('consent', 'update', {
                            'personalization_storage': 'denied',
                        });
                    }
                    if (cc.allowedCategory('security')) {
                        gtag('consent', 'update', {
                            'security_storage': 'granted'
                        });
                    }
                    if (!cc.allowedCategory('security')) {
                        gtag('consent', 'update', {
                            'security_storage': 'denied'
                        });
                    }
                },
           languages: {
                    'en': {
                        consent_modal: {
                            title: 'We use cookies!',
                            description: 'Hi, this website uses essential cookies to ensure its proper operation and tracking cookies to understand how you interact with it. The latter will be set only after consent. <button type="button" data-cc="c-settings" class="cc-link">Let me choose</button>',
                            primary_btn: {
                                text: 'Accept all',
                                role: 'accept_all'              // 'accept_selected' or 'accept_all'
                            },
                            secondary_btn: {
                                text: 'Reject all',
                                role: 'accept_necessary'        // 'settings' or 'accept_necessary'
                            }
                        },
                        settings_modal: {
                            title: 'Cookie preferences',
                            save_settings_btn: 'Save settings',
                            accept_all_btn: 'Accept all',
                            reject_all_btn: 'Reject all',
                            close_btn_label: 'Close',
                            cookie_table_headers: [
                                { col1: 'Name' },
                                { col2: 'Domain' },
                                { col3: 'Expiration' },
                                { col4: 'Description' }
                            ],
                            blocks: [
                                {
                                    title: 'Cookie usage ?',
                                    description: 'I use cookies to ensure the basic functionalities of the website and to enhance your online experience. You can choose for each category to opt-in/out whenever you want. For more details relative to cookies and other sensitive data, please read the full <a href="#" class="cc-link">privacy policy</a>.'
                                }, {
                                    title: 'Strictly necessary cookies',
                                    description: 'These cookies are essential for the proper functioning of my website. Without these cookies, the website would not work properly',
                                    toggle: {
                                        value: 'functionality',
                                        enabled: true,
                                        readonly: true          // cookie categories with readonly=true are all treated as "necessary cookies"
                                    }
                                }, {
                                    title: 'Performance and Analytics cookies',
                                    description: 'These cookies allow the website to remember the choices you have made in the past',
                                    toggle: {
                                        value: 'analytics',     // your cookie category
                                        enabled: false,
                                        readonly: false
                                    },
                                    cookie_table: [             // list of all expected cookies
                                        {
                                            col1: '^_ga',       // match all cookies starting with "_ga"
                                            col2: 'google.com',
                                            col3: '2 years',
                                            col4: 'description ...',
                                            is_regex: true
                                        },
                                        {
                                            col1: '_gid',
                                            col2: 'google.com',
                                            col3: '1 day',
                                            col4: 'description ...',
                                        }
                                    ]
                                }, {
                                    title: 'Advertisement and Targeting cookies',
                                    description: 'These cookies collect information about how you use the website, which pages you visited and which links you clicked on. All of the data is anonymized and cannot be used to identify you',
                                    toggle: {
                                        value: 'advertising',
                                        enabled: false,
                                        readonly: false
                                    }
                                }, {
                                    title: 'Personalization cookies',
                                    description: 'These cookies collect information about how you use the website, which pages you visited and which links you clicked on. All of the data is anonymized and cannot be used to identify you',
                                    toggle: {
                                        value: 'personalization',
                                        enabled: false,
                                        readonly: false
                                    }
                                }, {
                                    title: 'Security cookies',
                                    description: 'These cookies collect information about how you use the website, which pages you visited and which links you clicked on. All of the data is anonymized and cannot be used to identify you',
                                    toggle: {
                                        value: 'security',
                                        enabled: false,
                                        readonly: false
                                    }
                                }, {
                                    title: 'More information',
                                    description: 'For any queries in relation to our policy on cookies and your choices, please <a class="cc-link" href="#yourcontactpage">contact us</a>.',
                                }
                            ]
                        }
                    }
                }
            });
        });
</script>

And after this code, add the Google Tag Manager optional body code:

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=xxx-xxxxxx" height="0" width="0"
        style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
Adding Cookie Consent Code to WP body

Go to the frontend of your website and hit the refresh. You will see that Cookie bar appears! Hurrey! It also disable Google Analytics Cookies out of the box, because of the consent mode we set up earlier.

Cookie notice bar appears

Pro TIP ?

Do you want to clean up your websites code?

  1. Don’t add the Cookie Consent code to the Advanced scripts.
  2. Instead create a mycookieconsent.js and insert the code without the <script> tags inside.
  3. Then upload the file to the FTP to /wp-content/uploads/customscripts/cookies/ folder
  4. Use advanced scripts to include this file in your website’s body with wp_body_open hook.
  5. Then just add the Google Tag Manager body code with Advanced scripts.

Finally, it will look like this in your advanced scripts:

And you wouldn’t have this in your site body:

When adding script directly to advanced scripts it is added inline to body of website.

Add scripts outside Google Tag Manager (inline scripts) if needed

If you use other scripts in your websites code – for example in your template when you do not use Oxygen, just edit the scripts to type=”text/plain” and add the data-cookiecategory=”<category>”. You can find the how to in Cookie Consent documentation.

If you have custom scripts in your Google Tag Manager, just let them in and use this method too. For example, I have some tracking codes in GTM and they are custom and not compatible with Google Consent API. I have to switch their type and add the cookie category. Also I need to double check my Cookie consent bar settings if page_scripts:true is set.

Custom scripts in Google Tag Manager set to text/plain

Easy, huh? :)

Meta Pixel (Facebook pixel) Integration

If you want to use Facebook (Meta) Pixel, you should be using facebook consent API. This api needs to put the fbq(‘consent’, ‘grant’) or fbq(‘consent’, ‘revoke’) before init function of pixel code.

// Revoke consent before 'init' is called
fbq('consent', 'revoke');
fbq('init', '<your pixel ID>');
fbq('track', 'PageView');

Basically it does not delete the fbp cookie, but it disable the tracking code from sending any data to Meta (facebook).

Go to the Tag Manager and open your Facebook Pixel Code and add the fb consent settings before init.

fbq('consent', 'revoke');

This code will look like this:

<script>
  //your existing facebook code:
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}
  (window, document,'script','https://connect.facebook.net/en_US/fbevents.js');
  
  // fb consent
  fbq('consent', 'revoke'); 
  
  // rest of your existing facebook code:
  fbq('init', 'Your Facebook Pixel ID');
  fbq('track', 'PageView');
</script>
Facebook Pixel tag in GTM

Because we use the fbq(‘consent’, ‘grant’); and fbq(‘consent’, ‘revoke’); in the onAccept and onChange functions, it is now completely GDPR compliant.

That’s it?

Yep, that’s it. But do not forget about other things, which can also use cookies:

Add a text link component in Oxygen Builder and add a parameters to create opening link:

<a href="#cookie-settings" target="_self" data-cc="c-settings" aria-haspopup="dialog">Cookie Settings</a>
  1. Create Text link
  2. Add url address > #cookie-settings
  1. Go to advanced > attributes and add attributes
    1. data-cc=c-settings
    2. aria-haspopup=dialog

That’s everything. You can use code block for that, button element, link wrapper.. It’s up to you, how creative you will be.

How to test if cookies are loading or not

In Google Chrome Dev tools, go to the Application tab, click on the last cookie and hold DELETE key to delete them All. After that, reload

Cookies being loaded

After that, do a hard reload of page with CTRL + SHIFT + F5 and take a look again:

Cookies not being loaded

And after clicking Accept cookies:

Google Anlalytics loaded after accepting cookies

If you have questions take a look at the Github page of Orest Bida Cookie Consent or add a comment below this article! I will be happy to help.

Fuel my passion for writing with a beer🍺

Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻

10 comments

  • This is a fab walkthrough. Thank you!

    With this set up, I tried to add a community tag (not a third party script via custom HTML), and set the “Additional consent checks” in the tag options, but it just wouldn’t fire. Do you have any experience with that? It would be amazing to be able to leverage the Google Tag Manager options like this, because it would allow for the built-in auditing tools.

    In an ideal world, I would love to have this all held within Google Tag Manager. But that is perhaps a step after resolving the above!

  • Thank you! This is really helpful. Is there a tutorial on how to setup the Google consent in Google Tag Manager?

    This part:

    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }

    gtag(‘consent’, ‘default’, {
    ‘ad_storage’: ‘denied’,
    ‘analytics_storage’: ‘denied’,
    ‘functionality_storage’: ‘granted’,
    ‘personalization_storage’: ‘denied’,
    ‘security_storage’: ‘denied’,
    });

    How was this Google consent setup and where did you get that code?
    I did google it, but still no luck on how to set that up. It will be great if you can point me in the right direction or provide us some instructions.

    Thank you!

  • Thanks for the guide I am having issues I am trying not to use google tag manager and just have them read inline from another advancedscript file containing the scripts i.e

    or

    async onload=”HockeyStack.init(‘XXXXX’)” src=”https://cdn.jsdelivr.net/npm/hockeystack@latest/hockeystack.min.js”

    But they’re just not updating when the cookie is accepted

    Would it be possible to get a working example on how to do the above?

  • Many thanks for your job.
    I have a question regarding custom scripts on GTM.

    You said:

    “If you have custom scripts in your Google Tag Manager, just let them in and use this method too. For example, I have some tracking codes in GTM and they are custom and not compatible with Google Consent API. I have to switch their type and add the cookie category. Also I need to double check my Cookie consent bar settings if page_scripts:true is set.”

    Also your related picture is showing them.

    But when I put them into GTM they are not catched by cookie-consent-bar and they does not appear on the page source code.

    Is there any hint I miss to let them be present in GTM and managed through cookie consent bar? I need to put them into GTM and not on my CMS.

    Many thanks

  • A

    Hello Rose, with my setup, I don’t need to add any cookie storages to GTM. Just the datalayer push before loading gtm. Then, for Google Analytics, it works Out of the box. No _ga loaded before consent. You have propably did something wrong or my tutorial is not that easy understandable because of my english, i am sorry.

  • Thank you! I have managed to set the Google consent mode initialization in Google tag manager.
    I have added the 5 cookie storages:
    -ad_storage
    -personalization_storage
    -analytics_storage
    -functionality_storage
    -security_storage

    same as your screenshot/figure ‘Google Consent Mode storage settings in Tag settings’

    When I added all the cookie consent codes to the site, it works. The consent box shows up.
    Also, this is the google consent mode code that I’ve added in

    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }

    gtag(‘consent’, ‘default’, {
    ‘ad_storage’: ‘denied’,
    ‘analytics_storage’: ‘denied’,
    ‘functionality_storage’: ‘granted’,
    ‘personalization_storage’: ‘denied’,
    ‘security_storage’: ‘denied’,
    });

    However, whenever I go to the website and when I check on the cookies under the ‘View site information’ (I clicked on the lock icon in the address bar

    to view the site information), it has 2 ‘_ga’ cookies already added by default (I didn’t set the cookie settings yet).
    It seems those are the main cookies used by Google Analytics.
    Example:

    mydomain.ca
    > “Cookies” folder
    >> _ga
    >> _ga_XXXXXXX

    I thought those cookies (_ga, _ga_XXXXXXX ) shouldn’t be added if the ‘analytics_storage’ is not accepted yet.
    Is there a way to not let the site save those ‘_ga’ cookies on users visit the site? Those should only be saved once ‘analytics_storage’ cookie is accepted.

    Thanks!

  • A

    Hello Nathan, how do you add the community tag in tag manager? Like custom script?

    You need to know, that Google Consent Mode needs to be supported by the Tag at first. It currently works out of the box only with Google Analytics tags.
    Not with other tags like custom scripts. That’s why you should work with scripts in custom tags same way like with 3rd party scripts. In the future, there may be some better setup in GTM to work with additional consent, but for now, it is still in beta and doesn’t support behavior which you mention.

    I would love to use it in same way as you want, but no solution right now :).

  • A

    Hey, I have no idea what do you want. The gtag consent default state needs to be placed to the website, not to the Tag Manager. And this code sets up the default Google Consent in tag manager. The documentation is here: https://developers.google.com/tag-platform/devguides/consent

  • A

    Hey Nathan, did you added type=”text/plain” and add the data-cookiecategory=”” to the script?

    Do you load the script after cookie consent script?

  • A

    Hey! Have you tried it?

    Just put the custom script in GTM and change script to text plain and add the coresponding data-cookiecategory=”“.

    I am using the smartsupp and smartlook exactly like that. All scripts in GTM and Cookie Consent script in advanced scripts in wordpress.

    (You can also embed the whole Cookie Consent script into Google Tag Manager BTW.)

    Only thing you need to set up right is cookie table inside orestbida cookie consent if you want to enable automatic delete of cookies when consent is declined afterwards.

Share Your Thoughts