How to Add an Anti Adblock script in Wordpress

How to detect Adblocker in WordPress

Do you want to prevent Adblockers on your Wordpress website and boost your earnings, then this article is for you.

In this article, I will show you the easiest way of detecting Adblocker in Wordpress and forcing users to disable adblocker on your website.

So, what is Adblocker, and why you should use an Anti Adblocker script on your Website?

Well, Adblockers are mostly browser extensions that are designed to block ads on a page and load pages without ad codes.

So, if a user uses an Adblocker extension on their website then the ads will not display to that user and you will not get any ad click or impression from that person’s visit. Eventually, it may affect your overall ad income on that website.

It is now a serious issue as more people are now using this to have a clean experience but it is not good for creators like us whose websites mostly rely on Ad income.

Even very big popular websites like Google, YouTube, Facebook are mostly relying on Ads. As a content creator, you can ask your audience to disable ads on your website. As the content is free, users should not have any issue seeing some ads.

Recently, I have published a video on how to add anti adblock script in Blogger and some people request me to make a tutorial on how to implement it on the Wordpress website. So, follow the step-by-step tutorials below.

Youtube video

How to Install Anti Adblock script in Wordpress?

  1. To install the anti adblock script in Wordpress, login to your dashboard and go to Appearance > Theme File editor.
  2. Now open the Footer.php file and search for </body> tag.
  3. After that paste the script just above it.
  4. Then update the theme code and it is done.
Add anti AdBlock script in WordPress theme editor
<style>
.note{position:relative;padding:20px 30px 20px 50px;background-color:#e1f5fe;color:#01579b;font-size:.85rem;line-height:1.62em;border-radius:2px}
.note:before{content:'\2605';position:absolute;left:18px;font-size:20px}
.noteAlert{background-color:#ffdfdf;color:#e65151}
.noteAlert:before{content:'\2691'}
</style>
<script>//<![CDATA[ 
!function() {function f() {var a=document.getElementById("main");a.innerHTML='<p class="note noteAlert blocked"><strong>Ad-Block Detected :((</strong><br><br>Sorry, We detected that you have activated Ad-Blocker. <br> Please Consider supporting us by disabling your Ad-Blocker,It helps us in maintaining this website. <br>To View the content disable adblocker and refresh the page.<br><br>Thank You !!!</p>';} var b=document.createElement("script");b.type="text/javascript";b.async=!0;b.src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";b.onerror=function() {f();window.adblock=!0};var e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(b,e)}(); 
//]]></script>

Note: If the above code is not working then you have to replace the id (i.e. main) of your main content that is used on your theme.

If you don’t want to add it to the theme file editor, then you can add a code manager plugin like WPCode – WordPress Code Manager to your website.

WP-Code-Insert-Headers-and-Footers

Using this plugin you can add the code in the header section of your Wordpress website.

If you are using any AdSense plugin like Adinserter then you can also use that plugin to add the code in the footer section.

Just add the code in one of the boxes and set the placement to the footer.

Add anti adblock script in wordpress

So, in this way, you can detect Adblocker users on your Wordpress website and force them to unblock the adblocker tool.

Updated Anti Adblock Script for Wordpress (2026)

Youtube video

Code to Display Anti Adblock Notice popup to Users using Adblocker Extension.

<script>
(function () {
    'use strict';
    var CONFIG = {
        NETWORK_TIMEOUT: 3500,
        CONNECTIVITY_TIMEOUT: 2500,
        COSMETIC_DELAY: 300,
        BLOCK_THRESHOLD: 4,
        DEBUG: false
    };
    var started = false;
    var popupHost = null;

    function sleep(ms) {
        return new Promise(function (resolve) {
            setTimeout(resolve, ms);
        });
    }
    function randomName() {
        return 'x' + Math.random().toString(36).slice(2) + Date.now().toString(36);
    }
    function debugLog() {
        if (!CONFIG.DEBUG || !window.console || !console.debug) {
            return;
        }
        try {
            console.debug.apply(console, arguments);
        } catch (e) {}
    }
    function nextPaint() {
        return new Promise(function (resolve) {
            if (typeof requestAnimationFrame === 'function') {
                requestAnimationFrame(function () {
                    requestAnimationFrame(resolve);
                });
                return;
            }
            setTimeout(resolve, 32);
        });
    }
    function isHttpPage() {
        return location.protocol === 'http:' || location.protocol === 'https:';
    }
    function sameHost(a, b) {
        try {
            return new URL(a, location.href).host === new URL(b, location.href).host;
        } catch (e) {
            return false;
        }
    }
    function watchCspFor(url) {
        var hit = false;

        function onViolation(event) {
            var blockedUri = event && event.blockedURI ? String(event.blockedURI) : '';

            if (blockedUri && sameHost(blockedUri, url)) {
                hit = true;
            }
        }
        window.addEventListener('securitypolicyviolation', onViolation, true);

        return {
            wasHit: function () {
                return hit;
            },
            stop: function () {
                window.removeEventListener('securitypolicyviolation', onViolation, true);
            }
        };
    }
    function testScriptResource(url, name) {
        return new Promise(function (resolve) {
            var link = document.createElement('link');
            var csp = watchCspFor(url);
            var finished = false;
            var timer = null;

            function finish(status) {
                if (finished) {
                    return;
                }
                finished = true;
                clearTimeout(timer);
                csp.stop();
                link.onload = null;
                link.onerror = null;
                try {
                    link.remove();
                } catch (e) {}
                resolve({
                    name: name,
                    status: csp.wasHit() ? 'csp' : status
                });
            }
            timer = setTimeout(function () {
                finish('timeout');
            }, CONFIG.NETWORK_TIMEOUT);

            link.rel = 'preload';
            link.as = 'script';
            link.referrerPolicy = 'no-referrer';
            link.onload = function () {
                finish('loaded');
            };
            link.onerror = function () {
                setTimeout(function () {
                    finish('error');
                }, 40);
            };
            link.href = url + (url.indexOf('?') === -1 ? '?' : '&') + 'abcb=' + Date.now();
            try {
                (document.head || document.documentElement).appendChild(link);
            } catch (e) {
                finish('error');
            }
        });
    }
    function testPageConnectivity() {
        if (!isHttpPage()) {
            return Promise.resolve(null);
        }
        if (navigator.onLine === false) {
            return Promise.resolve(false);
        }
        return new Promise(function (resolve) {
            var controller = typeof AbortController !== 'undefined'
                ? new AbortController()
                : null;
            var csp = watchCspFor(location.href);
            var finished = false;
            var timer = null;
            function finish(value) {
                if (finished) {
                    return;
                }
                finished = true;
                clearTimeout(timer);
                csp.stop();
                resolve(csp.wasHit() ? null : value);
            }
            timer = setTimeout(function () {
                if (controller) {
                    controller.abort();
                }
                finish(false);
            }, CONFIG.CONNECTIVITY_TIMEOUT);
            var options = {
                method: 'HEAD',
                cache: 'no-store',
                credentials: 'same-origin'
            };
            if (controller) {
                options.signal = controller.signal;
            }
            fetch(location.href, options)
                .then(function () {
                    finish(true);
                })
                .catch(function () {
                    /* Avoid racing a CSP violation event. */
                    setTimeout(function () {
                        finish(false);
                    }, 40);
                });
        });
    }
    function elementLooksHidden(element) {
        if (!element || !element.isConnected) {
            return true;
        }
        try {
            var style = window.getComputedStyle(element);
            var rect = element.getBoundingClientRect();
            var opacity = parseFloat(style.opacity);
            return style.display === 'none'
                || style.visibility === 'hidden'
                || (!Number.isNaN(opacity) && opacity === 0)
                || rect.width < 1
                || rect.height < 1
                || element.offsetWidth < 1
                || element.offsetHeight < 1;
        } catch (e) {
            return true;
        }
    }
    async function testCosmeticFiltering() {
        if (!document.body) {
            return { status: 'inconclusive', hidden: 0, total: 0 };
        }
        var wrapper = document.createElement('div');
        var control = document.createElement('div');
        var baits = [];
        var suffix = randomName();
        wrapper.setAttribute('aria-hidden', 'true');
        wrapper.style.position = 'absolute';
        wrapper.style.left = '-10000px';
        wrapper.style.top = '-10000px';
        wrapper.style.width = '32px';
        wrapper.style.height = '32px';
        wrapper.style.pointerEvents = 'none';
        control.className = randomName();
        control.style.width = '12px';
        control.style.height = '12px';
        var definitions = [
            { tag: 'div', id: '', className: 'adsbox' },
            { tag: 'ins', id: '', className: 'adsbygoogle' },
            { tag: 'div', id: 'google_ads_' + suffix, className: 'advertisement' },
            { tag: 'div', id: '', className: 'ad-banner ad-container banner-ad sponsored-ad' }
        ];
        definitions.forEach(function (definition, index) {
            var bait = document.createElement(definition.tag);
            if (definition.id) {
                bait.id = definition.id;
            }
            bait.className = definition.className;
            bait.setAttribute('data-ad', 'true');
            bait.setAttribute('data-ad-slot', String(1000 + index));
            bait.style.position = 'absolute';
            bait.style.left = String(index * 14) + 'px';
            bait.style.top = '0';
            bait.style.width = '12px';
            bait.style.height = '12px';
            baits.push(bait);
            wrapper.appendChild(bait);
        });
        wrapper.appendChild(control);
        document.body.appendChild(wrapper);
        await nextPaint();
        await sleep(CONFIG.COSMETIC_DELAY);
        var controlHidden = elementLooksHidden(control);
        var hiddenCount = baits.reduce(function (count, bait) {
            return count + (elementLooksHidden(bait) ? 1 : 0);
        }, 0);
        try {
            wrapper.remove();
        } catch (e) {}
        if (controlHidden) {
            return {
                status: 'inconclusive',
                hidden: hiddenCount,
                total: baits.length
            };
        }
        return {
            status: hiddenCount > 0 ? 'blocked' : 'clear',
            hidden: hiddenCount,
            total: baits.length
        };
    }
    function networkPoints(result, connectivity) {
        if (!result || connectivity === false) {
            return 0;
        }
        if (result.status === 'error') {
            return 2;
        }
        if (result.status === 'timeout') {
            return 1;
        }
        return 0;
    }
    async function detectAdblock() {
        var results = await Promise.all([
            testScriptResource(
                'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js',
                'googleAds'
            ),
            testScriptResource(
                'https://securepubads.g.doubleclick.net/tag/js/gpt.js',
                'doubleClick'
            ),
            testCosmeticFiltering(),
            testPageConnectivity()
        ]);
        var googleAds = results[0];
        var doubleClick = results[1];
        var cosmetic = results[2];
        var connectivity = results[3];
        var score = 0;
        score += networkPoints(googleAds, connectivity);
        score += networkPoints(doubleClick, connectivity);
        if (cosmetic.status === 'blocked') {
            score += cosmetic.hidden >= 2 ? 4 : 3;
        }
        var output = {
            blocked: score >= CONFIG.BLOCK_THRESHOLD,
            score: score,
            signals: {
                googleAds: googleAds.status,
                doubleClick: doubleClick.status,
                cosmetic: cosmetic.status,
                cosmeticHidden: cosmetic.hidden,
                cosmeticTotal: cosmetic.total,
                pageConnectivity: connectivity
            }
        };
        debugLog('[adblock-detector]', output);
        return output;
    }
    function showPopup() {
        if (popupHost) {
            return;
        }
        var host = document.createElement('div');
        var shadow;
        var wrapper = document.createElement('div');
        var overlayClass = randomName();
        var cardClass = randomName();
        var iconClass = randomName();
        var buttonClass = randomName();
        var titleClass = randomName();
        var textClass = randomName();
        var smallClass = randomName();
        var style = document.createElement('style');
        var oldHtmlOverflow = document.documentElement.style.overflow;
        var oldBodyOverflow = document.body ? document.body.style.overflow : '';
        host.id = randomName();
        host.style.setProperty('position', 'fixed', 'important');
        host.style.setProperty('inset', '0', 'important');
        host.style.setProperty('z-index', '2147483647', 'important');
        host.style.setProperty('display', 'block', 'important');
        document.documentElement.appendChild(host);
        try {
            shadow = host.attachShadow({ mode: 'closed' });
        } catch (e) {
            host.remove();
            popupHost = null;
            return;
        }
        style.textContent = `
            .${overlayClass} {
                position: fixed;
                inset: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                box-sizing: border-box;
                padding: 22px;
                background: rgba(15, 18, 25, .82);
                backdrop-filter: blur(10px);
                -webkit-backdrop-filter: blur(10px);
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            }

            .${cardClass} {
                position: relative;
                width: min(440px, 100%);
                box-sizing: border-box;
                padding: 34px 30px 28px;
                border: 1px solid rgba(255,255,255,.15);
                border-radius: 20px;
                background: #fff;
                color: #17191f;
                text-align: center;
                box-shadow: 0 25px 80px rgba(0,0,0,.38);
                animation: aaEnter .28s ease-out;
            }

            @keyframes aaEnter {
                from { opacity: 0; transform: translateY(15px) scale(.97); }
                to { opacity: 1; transform: translateY(0) scale(1); }
            }

            .${iconClass} {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 68px;
                height: 68px;
                margin: 0 auto 21px;
                border-radius: 50%;
                background: #fff0f0;
                font-size: 31px;
                line-height: 1;
            }

            .${titleClass} {
                margin: 0 0 12px;
                color: #17191f;
                font-size: 24px;
                line-height: 1.25;
                font-weight: 750;
            }

            .${textClass} {
                margin: 0 auto 24px;
                max-width: 360px;
                color: #60646c;
                font-size: 15px;
                line-height: 1.65;
            }

            .${buttonClass} {
                width: 100%;
                box-sizing: border-box;
                border: 0;
                border-radius: 11px;
                padding: 14px 20px;
                background: #17191f;
                color: #fff;
                cursor: pointer;
                font-size: 15px;
                font-weight: 650;
                transition: transform .15s ease, opacity .15s ease;
            }
            .${buttonClass}:hover { transform: translateY(-1px); }
            .${buttonClass}:active { transform: translateY(0); }
            .${buttonClass}:focus-visible { outline: 3px solid #7b82ff; outline-offset: 3px; }
            .${buttonClass}:disabled { cursor: default; opacity: .55; }
            .${smallClass} {
                margin: 17px 0 0;
                color: #979ba4;
                font-size: 12px;
                line-height: 1.5;
            }
            @media (prefers-reduced-motion: reduce) {
                .${cardClass} { animation: none; }
                .${buttonClass} { transition: none; }
            }
        `;
        wrapper.className = overlayClass;
        wrapper.innerHTML = `
            <div class="${cardClass}" role="dialog" aria-modal="true" aria-labelledby="aa-title" aria-describedby="aa-text">
                <div class="${iconClass}" aria-hidden="true">🛡️</div>
                <h2 id="aa-title" class="${titleClass}">Please allow ads to continue</h2>
                <p id="aa-text" class="${textClass}">
                    It looks like an ad blocker or browser privacy feature is preventing our ads from loading.
                    <br><br>
                    Ads help us keep this content available without charging you. Please allow ads for this website, then check again.
                </p>
                <button type="button" class="${buttonClass}">I've allowed ads — check again</button>
                <p class="${smallClass}">Using Brave? Turn off Shields for this site, then press the button above.</p>
            </div>
        `;
        shadow.appendChild(style);
        shadow.appendChild(wrapper);
        document.documentElement.style.setProperty('overflow', 'hidden', 'important');
        if (document.body) {
            document.body.style.setProperty('overflow', 'hidden', 'important');
        }
        var button = wrapper.querySelector('.' + buttonClass);
        button.addEventListener('click', async function () {
            button.disabled = true;
            button.textContent = 'Checking…';
            await sleep(250);
            var result = await detectAdblock();
            if (!result.blocked) {
                button.textContent = 'Ads allowed ✓';
                await sleep(350);
                location.reload();
                return;
            }
            button.disabled = false;
            button.textContent = 'Still blocked — check again';
        });
        host.__restoreOverflow = function () {
            document.documentElement.style.overflow = oldHtmlOverflow;
            if (document.body) {
                document.body.style.overflow = oldBodyOverflow;
            }
        };
        popupHost = host;
        try {
            button.focus({ preventScroll: true });
        } catch (e) {
            try { button.focus(); } catch (ignored) {}
        }
    }
    async function activate(event) {
        if (event.isTrusted !== true || started) {
            return;
        }
        started = true;
        window.removeEventListener('pointerdown', activate, true);
        window.removeEventListener('touchstart', activate, true);
        window.removeEventListener('touchmove', activate, true);
        window.removeEventListener('wheel', activate, true);
        window.removeEventListener('keydown', activate, true);
        await sleep(150);
        var result = await detectAdblock();
        if (result.blocked) {
            showPopup();
        }
    }
    window.addEventListener('pointerdown', activate, true);
    window.addEventListener('touchstart', activate, { capture: true, passive: true });
    window.addEventListener('touchmove', activate, { capture: true, passive: true });
    window.addEventListener('wheel', activate, { capture: true, passive: true });
    window.addEventListener('keydown', activate, true);
})();
</script>

Force users to Enable Javascript on browser

<noscript>
    <style>
        html, body {
            overflow: hidden !important;
        }

        #javascript-required {
            position: fixed;
            inset: 0;
            z-index: 2147483647;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 22px;
            box-sizing: border-box;
            background: rgba(15, 18, 25, .96);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI",
                         Roboto, Helvetica, Arial, sans-serif;
        }

        #javascript-required .card {
            width: min(440px, 100%);
            box-sizing: border-box;
            padding: 34px 30px 28px;
            border-radius: 20px;
            background: white;
            color: #17191f;
            text-align: center;
            box-shadow: 0 25px 80px rgba(0,0,0,.38);
        }

        #javascript-required h2 {
            margin: 0 0 12px;
            font-size: 24px;
        }

        #javascript-required p {
            margin: 0;
            color: #60646c;
            font-size: 15px;
            line-height: 1.65;
        }
    </style>

    <div id="javascript-required">
        <div class="card">
            <h2>JavaScript is required</h2>
            <p>
                JavaScript must be enabled to access this website.
                Please enable JavaScript for this site and reload the page.
            </p>
        </div>
    </div>
</noscript>

Best Anti Adblock WordPress Plugins

If you don’t want to use a script then you can directly add an anti adblock plugin in Wordpress. Here, are the 5 best plugins you can consider.

  • Ad Blocker Notify
  • AdBlock X
  • Ad Blocking Detector
  • Simple Adblock Notice
  • Block AdBlock

Some of the plugins are not tested with the latest version of Wordpress and as the adblockers are evolving frequently, the plugin might not work in some cases.

So, these plugins also do the same job as that of the above plugin but the way of adblock notice is different and shows a different style warning message to the users. But, I recommend you to use the above script as it is more efficient and doesn’t require an additional plugin.

FAQs

An anti-adblock script detects when a visitor is using an ad blocker and displays a notification asking them to disable it. This can help publishers recover ad impressions and revenue from visitors who block advertisements.

You can add the script directly to your WordPress theme’s footer.php file, just before the closing </body> tag. Alternatively, you can use a code management plugin to insert the script into the website footer.

No. The method explained in this tutorial uses JavaScript and does not require a dedicated anti-adblock plugin. You can also use a code management plugin if you prefer not to edit your theme files directly.

The script is designed to detect whether the Google AdSense ad script has been blocked and then display a warning message. However, ad-blocking technology changes frequently, so detection may not work perfectly with every browser or ad-blocking configuration.

Yes. You can edit the text inside the JavaScript code to create your own message. You can also modify the CSS to change the background color, text color, spacing, font size, and overall appearance of the warning box.

A small JavaScript snippet generally adds less overhead than installing a full plugin, but the actual impact depends on how the script is implemented and what external resources it loads. You should test your website’s performance after adding it.

Yes, it works with brave browser as well.

Yes, You can use the same code for blogger website as well.

Yes. Advanced ad blockers can sometimes detect or bypass anti-adblock scripts. Because both ad-blocking and anti-adblock techniques evolve continuously, no client-side detection method is guaranteed to work permanently.

Conclusion

If you have any issues during this process, then you can ask me in the comment section.

Keep in mind that no anti-adblock script can detect every ad blocker or guarantee permanent results. Ad-blocking extensions, privacy-focused browsers, and browser technologies are constantly changing.

If your website depends on advertising revenue, this technique can be worth trying. Just make sure the warning message is clear, non-intrusive, and gives your visitors a good reason to support your content.

Don’t forget to share this article with your Blogging community and help them earn more.

Similar Posts

4 Comments

  1. Hi key2blogging,

    Thanks for your time and support. Your videos have been greatly helpful. I’m using using publishable mag theme. I implemented the code for anti ads blocker but it doesn’t work. Can you please assist?

    1. Abhishek padhi says:

      Ad block notice show after visiting 2 pages on the website. Let me know which Ad blocker extension and browser you are using ??

  2. Does this blocker block only Google AdSense ads, or does it block Adsterra ads as well?

    1. Abhishek padhi says:

      No, This is only effective for Adsense Ads

Leave a Reply

Your email address will not be published. Required fields are marked *

Hostinger Hosting
Get 20% Discount on Checkout
Hostinger managed Wordpress hosting
Get 20% Discount on Checkout