# 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.

- Type: PHP
- Runs: Frontend only
- Category: [Privacy & Cookies](https://wpide.com/library/category/privacy/)
- Tags: consent, scripts, gdpr
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/privacy-hold-scripts-until-consent/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Hold Tracking Scripts Until the Visitor Consents" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
