Easy Cookie Consent

Example Cookie Consent

This tutorial is created for all people who try to set up their EU cookie consent with WordPress website, for this example I will be using the open-source Cookie Consent JS by Orest Bida

Stack for this tutorial:

- WordPress (Latest)
- Oxygen Builder [Although this method will work for other builders]
- Script Organizer [ If your using advanced scripts there is an excellent tutorial here which served as the inspiration for this one and where the code came from which has been modified, so I remember how to do it next time]

Loading the Scripts

The scripts are available on JSdelivr.net and in this example, we will use them from this CDN rather than host them locally but equally Script Organizer gives you the option to upload JS locally too, load Scripts Organizer and select Scripts Manager

Script Manager

First, we need to register the JS, So call the script what you want, type is Javascript, put it in the footer and make sure include type is register and then paste the CDN link we will also do the same for the CSS file

Script Manager Load JS

CSS File

We now need to register the CSS, So call the script what you want, type is CSS, put it in the footer and make sure include type is register and then paste the CDN link we will also do the same for the CSS file

Script Manager Load CSS

Now we need to go to Code Blocks within Scripts Organizer

Number 1 Below: We will be creating a new code block in my example I've called it cookie consent, Trigger Locations, Conditions, Script Location Header and Footer, Template All, Script Manager Show and Enqueue the CSS and JS file we added to Scripts Manager earlier

Code Block

Number 2 contains the code for google consent mode and google tag manager which I am not using but have included for those of you who after reading the documentation want to do so.

<!-- 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 -->

Number 3 contains the cookies we want to activate based on consent I have included two examples 1 is a basic JS cookie and the other activates a cookie for Hockey Stack that isn't cookieless

<!-- Cookies Go Here --->
<script type="text/plain" data-cookiecategory="advertising"> 
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC";
</script>
<script type="text/plain" data-cookiecategory="advertising" async data-apikey="API Here"  src="https://cdn.jsdelivr.net/npm/[email protected]/hockeystack.min.js"></script>
<!-- End of Cookies -->

The Footer Section contains the following code from the great-tit article linked above, I have made a single modification that is to allow the cookies to reactivate once consent has been given and that is to page scripts which should be set to TRUE

<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: true,                        // default: false *** You need this to be true if you want them to update***

            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>

Additional information on using cookie consent is available at Cookie Consent documentation.

Quick and Dirty ( Register the CSS and JS) and import this export file which you can download here

Thanks to Marko Krstic for assistance getting this working with Script Organiser, Great-tit.com for the inspiration article and the original code.

Hello world!

Welcome to WordPress. This is your first post. Edit or delete it, then start writing!