How track AI Chatbots with Matomo in WordPress without plugins

Matomo will alerts about that stuff, also suggesting to use the official plugin but if you are using a self hosted version is not the right choice, because that plugin will install inside WordPress a real Matomo instance!

The solution is to track server side the various requests using the various User Agent and redirecting this requests to your Matomo instance.

add_action('template_redirect', 'matomo_track_ai_chatbots');

function matomo_track_ai_chatbots() {

  if (is_admin()) {
    return;
  }

  $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';

  $bots = apply_filters('matomo_ai_chatbots', [
    'ChatGPT-User'         => 'ChatGPT',
    'Perplexity-User'      => 'Perplexity',
    'Claude-User'          => 'Claude',
    'Gemini-Deep-Research' => 'Gemini',
    'MistralAI-User'       => 'Mistral',
    'Google-NotebookLM'    => 'Google NotebookLM',
  ]);

  $detected_bot = null;

  foreach ($bots as $needle => $name) {

    if (stripos($ua, $needle) !== false) {
      $detected_bot = $name;
      break;
    }
  }

  if (!$detected_bot) {
    return;
  }

  send_matomo_ai_visit(
    $detected_bot,
    home_url($_SERVER['REQUEST_URI']),
    $ua
  );
}

function send_matomo_ai_visit($bot_name, $url, $ua) {

  $endpoint = 'https://yout-matomo-instance/matomo.php';

  wp_remote_post(
    $endpoint,
    [
      'timeout' => 2,
      'blocking' => false,
      'body' => [
        'idsite' => 1, // your site id
        'rec' => 1,
        'recMode' => '1',
        'url' => $url,
        'ua' => $ua
      ]
    ]
  );
}

The next if you are using a caching plugin is to ignore cache when matches the User Agent (like W3TC plugin as example):

ChatGPT-User
Claude-User
Gemini-Deep-Research
Google-NotebookLM
MistralAI-User
Perplexity-User

After this just wait a day and you will see the AI Chatbots graph filling with data!

Liked it? Take a second to support Mte90 on Patreon!
Become a patron at Patreon!

Leave a Reply

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