Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cabrerahector/da226391acd030b1269d99135e15e653 to your computer and use it in GitHub Desktop.
Save cabrerahector/da226391acd030b1269d99135e15e653 to your computer and use it in GitHub Desktop.
WordPress Popular Posts - Do Not Track Bots
<?php
/**
* Have WordPress Popular Posts avoid tracking
* visits generated by bots.
*/
function wpp_do_not_track_bot_visit() {
if ( is_singular() ) {
?>
<script>
/**
* Based off of https://fingerprint.com/blog/build-your-own-bot-detection-script/
*/
function detectBot() {
const detectors = {
webDriver: navigator.webdriver, // Checks if the browser is controlled by automation
headlessBrowser: navigator.userAgent.includes("Headless"), // Detects headless browsers
noLanguages: (navigator.languages?.length || 0) === 0, // Browser has no languages, uncommon for normal users
domManipulation: document.documentElement
.getAttributeNames()
.some((attr) => ["selenium", "webdriver", "driver"].includes(attr)), // Looks for attributes commonly added by automation tools
identifiesAsBot: /bot|spider|crawl|google|baidu|bing|msn|teoma|slurp|yandex|facebook|semrush|java|wget|curl/i.test(navigator.userAgent) // Checks if user agent identifies as bot
};
// 1. Stores the detection results and the final verdict
const detections = {};
let verdict = { bot: false };
// 2. Iterates over the detectors and sets the verdict to true if any of them detects bot-like activity
for (const detectorName in detectors) {
const detectorResult = detectors[detectorName];
detections[detectorName] = { bot: detectorResult };
if (detectorResult) {
verdict = { bot: true }; // Sets the verdict to true at the first detection of bot-like activity
}
}
// 3. Returns the detection results and the final verdict
return { detections, verdict };
}
const { verdict } = detectBot();
// This visitor is most likely a bot, do not track this page view
if ( verdict.bot ) {
window.wpp_do_request = false;
console.log('You are a bot');
}
</script>
<?php
}
}
add_action('wp_head', 'wpp_do_not_track_bot_visit', 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment