# TikTok Pixel

> Adds the TikTok pixel to every public page and records page views, with an option to wait for cookie consent.

- Type: PHP
- Runs: Frontend only
- Category: [Analytics & Tracking](https://wpide.com/library/category/analytics/)
- Tags: tiktok, pixel, ads, tracking
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/analytics-tiktok-pixel/

## Code

```php
add_action( 'wp_head', function () {
    $pixel_id        = 'YOUR_PIXEL_ID'; // TikTok pixel ID.
    $require_consent = false;           // true: wait for consent from the WPIDE cookie banner.

    if ( 'YOUR_PIXEL_ID' === $pixel_id || current_user_can( 'edit_posts' ) ) {
        return;
    }
    ?>
<script>
(function (run) {
    if (!<?php echo $require_consent ? 'true' : 'false'; ?> || /(?:^|; )wpide_consent=granted/.test(document.cookie)) { run(); return; }
    document.addEventListener('wpide:consent', function (e) { if (e.detail === 'granted') { run(); } });
})(function () {
    var id = <?php echo wp_json_encode( $pixel_id ); ?>;
    window.TiktokAnalyticsObject = 'ttq';
    var ttq = window.ttq = window.ttq || [];
    ttq.methods = ['page', 'track', 'identify', 'instances', 'debug', 'on', 'off', 'once', 'ready', 'alias', 'group', 'enableCookie', 'disableCookie', 'holdConsent', 'revokeConsent', 'grantConsent'];
    ttq.setAndDefer = function (target, method) {
        target[method] = function () { target.push([method].concat(Array.prototype.slice.call(arguments, 0))); };
    };
    ttq.methods.forEach(function (method) { ttq.setAndDefer(ttq, method); });
    ttq.instance = function (name) {
        var inst = ttq._i[name] || [];
        ttq.methods.forEach(function (method) { ttq.setAndDefer(inst, method); });
        return inst;
    };
    ttq.load = function (pixel, options) {
        var url = 'https://analytics.tiktok.com/i18n/pixel/events.js';
        ttq._i = ttq._i || {}; ttq._i[pixel] = []; ttq._i[pixel]._u = url;
        ttq._t = ttq._t || {}; ttq._t[pixel] = +new Date();
        ttq._o = ttq._o || {}; ttq._o[pixel] = options || {};
        var s = document.createElement('script');
        s.async = true;
        s.src = url + '?sdkid=' + encodeURIComponent(pixel) + '&lib=ttq';
        document.head.appendChild(s);
    };
    ttq.load(id);
    ttq.page();
});
</script>
    <?php
} );
```

## Notes

Replace YOUR_PIXEL_ID with the pixel ID from TikTok Ads Manager > Assets > Events. Nothing is output while the placeholder is in place.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "TikTok Pixel" 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/
