TikTok Pixel
Adds the TikTok pixel to every public page and records page views, with an option to wait for cookie consent.
Opens WPIDE on
Code
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 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.