Show Embeds Only After Consent With a Shortcode
Wraps any embed or HTML in [consent_content category="marketing"]...[/consent_content] so it stays hidden behind a short notice until the visitor consents, using the WP Consent API when available.
Opens WPIDE on
Code
add_shortcode( 'consent_content', function ( $atts, $content = '' ) {
static $script = false;
$atts = shortcode_atts( array(
'category' => 'marketing',
'notice' => 'This content is provided by a third party that may set cookies.',
), $atts, 'consent_content' );
if ( '' === trim( (string) $content ) ) {
return '';
}
$html = sprintf(
'<div class="wpide-consent-box" data-category="%1$s"><template>%2$s</template><div class="wpide-consent-note" style="padding:16px;border:1px solid #ccc;background:#f6f7f7;"><p style="margin:0 0 8px">%3$s</p><button type="button" class="wpide-consent-load">Load content</button></div></div>',
esc_attr( sanitize_key( $atts['category'] ) ),
do_shortcode( $content ),
esc_html( $atts['notice'] )
);
if ( ! $script ) {
$script = true;
$html .= '<script>(function(){function ok(c){if(typeof window.wp_has_consent==="function"){return window.wp_has_consent(c);}return /(?:^|; )wpide_consent=granted/.test(document.cookie);}function show(box){var t=box.querySelector("template");if(!t){return;}box.replaceChildren(t.content.cloneNode(true));}function run(){document.querySelectorAll(".wpide-consent-box").forEach(function(b){if(ok(b.getAttribute("data-category"))){show(b);}});}document.addEventListener("click",function(e){var b=e.target.closest(".wpide-consent-load");if(b){show(b.closest(".wpide-consent-box"));}});document.addEventListener("wp_listen_for_consent_change",run);document.addEventListener("wpide:consent",run);if(document.readyState!=="loading"){run();}else{document.addEventListener("DOMContentLoaded",run);}})();</script>';
}
return $html;
} );
Notes
The notice offers a "Load content" button that unlocks this item only; full consent still comes from your cookie banner.
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.