Block specific user agents and referrers from being tracked

We provide the code snippets and content on this page without any guarantee or support. In most cases, these pages are created on requests or based on individual solutions sent to us by other users. After it was published, we are only reviewing the code and content when we are made aware of an issue. Please let us know if you find one.

Please only use the codes if you understand them and know how to add custom code to your WordPress site.

The following code allows you to block specific user agents or referrers from being tracked with the Tracking add-on. It was written for a very specific use case in mind but can still serve you as a basis to implement your own, custom filter.

add_filter( 'advanced-ads-tracking-do-tracking',  'my_advads_tracking_filter', 10, 3 );
function my_advads_tracking_filter( $status, $ad_id, $table ) {
    
    // possible harmful user agents, can be partial
    $blocked_user_agents = array(
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538',
        'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538',
    );
    
    // possible harmful referrers
    $blocked_referrers = array(
        'example.com',
    );
    
    // only check clicks, use 'impressions' for impressions 
    // or remove the condition to check clicks and impressions
    if( $table && strpos( $table, 'clicks' ) ) {
 
        $block_user_agent = false;
        $block_referrer = false;

        // check user agent
        if (isset($_SERVER['HTTP_USER_AGENT']) && '' !== $_SERVER['HTTP_USER_AGENT']) {
            $agent = sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT']));

            foreach( $blocked_user_agents as $_agent ) {
                // stop after the first matching user agent we found
                if( false !== strpos( $agent, $_agent ) ) {
                    $block_user_agent = true;
                    break;
                }
            }
        }
     
         // check referrer
         if (isset($_SERVER['HTTP_REFERER']) && '' !== $_SERVER['HTTP_REFERER']) {
            $referrer = sanitize_text_field(wp_unslash($_SERVER['HTTP_REFERER']));
         
            foreach( $blocked_referrers as $_referrer ) {
                // stop after the first matching user agent we found
                if( false !== strpos( $referrer, $_referrer ) ) {
                    $block_referrer = true;
                    break;
                }
            }
         }
         
         // only block the click if we found a blocked user agent AND referrer
         if( $block_user_agent && $block_referrer ){
             return false;
         }
    }
    return $status; 
}Code language: PHP (php)

Make it better

Increase your ad management skills without spending more time.
Join over 150,000 publishers and AdOpts increasing their ad revenue.