Steps to Add This to Your WordPress Site:
- Add the JavaScript Code to your theme’s
header.php
or enqueue it in yourfunctions.php
. - Create a CSS-styled message to inform users about ad blocking.
JavaScript Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <script> document.addEventListener("DOMContentLoaded", function () { // Create a hidden div that adblockers usually block let adDiv = document.createElement("div"); adDiv.className = "adsbygoogle"; adDiv.style. display = "none"; document.body.appendChild(adDiv); // Check if the element is being blocked setTimeout(() => { if (adDiv.offsetHeight === 0) { showAdBlockMessage(); } }, 500); function showAdBlockMessage() { let messageBox = document.createElement("div"); messageBox.innerHTML = ` <div id="adblock-message" style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border: 2px solid red; text-align: center; z-index: 10000;"> <h3>We've detected you're using an Ad Blocker</h3> <p>Please consider disabling it to support our website.</p> <button onclick="document.getElementById('adblock-message').remove()">Close</button> </div>`; document.body.appendChild(messageBox); } }); </script> |