This document provides technical details about how the Simple Cookie Consent plugin works, focusing on how it loads settings from the WordPress admin and blocks cookies until consent is given.
The plugin consists of three main components:
- PHP Admin Interface: Handles settings storage and retrieval in WordPress
- JavaScript Configuration: Configures the vanilla-cookieconsent library
- Cookie Consent Banner: User-facing interface for managing consent
When a user saves settings in the WordPress admin:
- Settings are stored in WordPress options table under the
scc_optionskey - The plugin validates all inputs using
scc_validate_options() - Default values are provided by
scc_get_default_options()if needed
When a page loads:
scc_enqueue_scripts()function loads the bundled JavaScript- The same function retrieves settings with
get_option('scc_options') wp_localize_script()passes these settings to JavaScript assccSettings.settings
wp_localize_script('scc-cookieconsent', 'sccSettings', array(
'settings' => $options,
'version' => time()
));In the src/index.js file:
- Default configuration is defined in the
configobject - WordPress settings are loaded from
window.sccSettings - The configuration is updated with user preferences:
// Example of how settings are merged
if (typeof window.sccSettings !== 'undefined') {
const wpSettings = window.sccSettings.settings;
// Update translations with WordPress settings
if (config.language.translations[config.language.default]) {
config.language.translations[config.language.default].consentModal.title =
wpSettings.title || config.language.translations[config.language.default].consentModal.title;
// Additional settings mapping...
}
}The plugin uses vanilla-cookieconsent's script blocking capabilities to prevent cookies from being set until consent is given.
- Scripts are marked with
data-cookiecategoryattributes to associate them with consent categories - The cookie consent library prevents these scripts from executing until the user gives consent for that category
- The
page_scripts: truesetting enables this functionality
<!-- This script won't run until 'analytics' consent is given -->
<script type="text/plain" data-cookiecategory="analytics">
// Google Analytics or other tracking code
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>When a user withdraws consent, related cookies can be automatically deleted:
- The
autoclear_cookiessetting enables this feature - Specific cookies to clear are defined in the configuration:
analytics: {
enabled: false,
readOnly: false,
autoClear: {
cookies: [
{
name: /^_ga/, // Regular expression to match cookies starting with _ga
},
{
name: '_gid', // Exact match for _gid cookie
}
]
}
}Here's how to implement Google Analytics with proper consent management:
- Add your Google Analytics code to your site with the appropriate data attribute:
<script type="text/plain" data-cookiecategory="analytics">
// Google Analytics code (GA4)
(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/gtag/js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','G-XXXXXXXXXX');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>- Ensure the analytics category is configured in the cookie consent setup:
analytics: {
enabled: false, // Disabled by default, requiring explicit consent
readOnly: false, // Can be toggled by the user
autoClear: {
cookies: [
{ name: /^_ga/ },
{ name: '_gid' },
{ name: '_gat' },
{ name: '_ga_.*' } // GA4 cookies
]
}
}To add a new cookie category (e.g., "marketing"):
- Add the category to the configuration object in
src/index.js:
categories: {
// ...existing categories...
marketing: {
enabled: false,
readOnly: false,
autoClear: {
cookies: [
{ name: /^mk_/ },
{ name: 'marketing_session' }
]
}
}
}- Add the UI elements for this category:
sections: [
// ...existing sections...
{
title: 'Marketing Cookies',
description: 'These cookies are used to track visitors across websites to display relevant advertisements.',
linkedCategory: 'marketing'
}
]- Mark scripts with the new category:
<script type="text/plain" data-cookiecategory="marketing">
// Marketing scripts here
</script>The cookie consent library provides several events you can hook into:
onConsent: ({cookie}) => {
console.log('Consent given:', cookie);
// Perform actions based on consent
},
onChange: ({changedCategories, changedServices}) => {
console.log('Consent changed for:', changedCategories);
// React to consent changes
}The plugin now allows you to manage cookie categories and specific cookie patterns through the WordPress admin interface.
You can add new cookie categories (e.g., marketing, preferences) through the admin interface:
- Go to Settings > Cookie Consent
- At the bottom of the Cookie Categories section, enter a new category ID (e.g., "marketing")
- Click "Add New Category"
- Configure the new category's settings (title, description, etc.)
- Save the settings
Each category will automatically appear as a new section in the cookie preferences modal.
You can specify which cookies should be blocked until consent is given:
- Go to Settings > Cookie Consent
- Find the relevant cookie category
- Enter a cookie name or pattern in the input field
- Check "Regular Expression" if you're using a pattern (e.g.,
/^_ga/will match all cookies starting with "_ga") - Click "Add Cookie"
Two types of cookie patterns are supported:
- Exact Match: Simple cookie names like "_gid" - these will match only the exact cookie name
- Regular Expression: Patterns like "/^_ga/" - these allow matching multiple cookies with similar patterns
Regular expressions should be entered with the forward slashes (e.g., /^_ga/). Some useful patterns:
/^_ga/- Match all cookies starting with "_ga"/analytics/- Match all cookies containing "analytics"/^__[a-z]/- Match all cookies starting with double underscore followed by a lowercase letter
When a user has not consented to a particular category:
- Scripts marked with
type="text/plain" data-cookiecategory="category_id"won't execute - Cookies matching patterns in that category will be automatically cleared if set
Example of a script that will only run with analytics consent:
<script type="text/plain" data-cookiecategory="analytics">
// Google Analytics code here
</script>Common issues and their solutions:
Check that:
- The script has the correct
type="text/plain"attribute - The
data-cookiecategoryvalue matches exactly with your category name - The
page_scriptssetting is enabled
Check that:
- The
autoclear_cookiessetting is enabled - Cookie names are correctly specified in the configuration
- The browser supports cookie deletion (some browsers restrict this)
If your WordPress settings aren't reflected in the cookie banner:
- Check the browser console for JavaScript errors
- Verify that
sccSettingsis properly loaded by adding a debug statement - Clear browser cache or add a version parameter to prevent caching
If you're using Google Tag Manager or similar services:
- Load the tag manager script with appropriate consent category:
<script type="text/plain" data-cookiecategory="analytics">
// Google Tag Manager
(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','GTM-XXXXXXX');
</script>- Set up consent mode in your tag manager to respect the cookie consent choices