Hold Tracking Scripts Until the Visitor Consents
Turns the scripts you list by handle into inactive placeholders and only runs them after the visitor gives consent, through the WP Consent API when a consent plugin provides it or the simple wpide_consent cookie otherwise.
Opens WPIDE on
Code
// Script handle => consent category (functional, preferences, statistics, marketing).
$wpide_consent_scripts = array(
'google-analytics' => 'statistics',
'facebook-pixel' => 'marketing',
);
add_filter( 'script_loader_tag', function ( $tag, $handle ) use ( $wpide_consent_scripts ) {
if ( empty( $wpide_consent_scripts[ $handle ] ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $tag;
}
$tags = new WP_HTML_Tag_Processor( $tag );
while ( $tags->next_tag( 'script' ) ) {
$tags->set_attribute( 'type', 'text/plain' );
$tags->set_attribute( 'data-wpide-consent', $wpide_consent_scripts[ $handle ] );
}
return $tags->get_updated_html();
}, 20, 2 );
add_action( 'wp_footer', function () {
?>
<script>
(function () {
function allowed(category) {
if (typeof window.wp_has_consent === 'function') { return window.wp_has_consent(category); }
return /(?:^|; )wpide_consent=granted/.test(document.cookie);
}
function release() {
document.querySelectorAll('script[type="text/plain"][data-wpide-consent]').forEach(function (old) {
if (!allowed(old.getAttribute('data-wpide-consent'))) { return; }
var s = document.createElement('script');
Array.prototype.forEach.call(old.attributes, function (a) {
if (a.name !== 'type' && a.name !== 'data-wpide-consent') { s.setAttribute(a.name, a.value); }
});
if (!old.src) { s.text = old.text; }
old.parentNode.replaceChild(s, old);
});
}
release();
document.addEventListener('wp_listen_for_consent_change', release);
document.addEventListener('wpide:consent', release);
})();
</script>
<?php
}, 99 );
Notes
Find script handles with a "list enqueued assets" snippet; scripts that other scripts depend on should not be held back.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.