Count access statistics for anonymous users only (Drupal 7)

Estimated reading time of this article: 1 minute 50 seconds

Do you want to count access statistics for anonymous visitors only? Do you want to reset access statistics for unpublished articles?

I'm assuming you're using the Drupal 7 statistics module.

Instead of copying the whole statistics module and changing it, there's a simple trick: Undo the +1 of registered users by an -1. Thus, the increase of the statistics module is compensated.

<?php
/**
 * Implements hook_exit().
 *
 * Compensate access statistics of registered users with -1.
 * See statistics_exit().
 */
function YOUR_MODULE_exit() {
  global
$user;

 
// When serving cached pages with the 'page_cache_without_database'
  // configuration, system variables need to be loaded. This is a major
  // performance decrease for non-database page caches, but with Statistics
  // module, it is likely to also have 'statistics_enable_access_log' enabled,
  // in which case we need to bootstrap to the session phase anyway.
 
drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES);

  if (
variable_get('statistics_count_content_views', 0)) {
   
// We are counting content views.
   
if ($user->uid != 0 && arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == NULL) {
     
// A node has been viewed, so update the node's counters.
     
db_merge('node_counter')
        ->
key(array('nid' => arg(1)))
        ->
fields(array(
         
'daycount' => 1,
         
'totalcount' => 1,
         
'timestamp' => REQUEST_TIME,
        ))
        ->
expression('daycount', 'GREATEST(daycount, 1) - 1')
        ->
expression('totalcount', 'GREATEST(totalcount, 1) - 1')
        ->
execute();
    }
  }
}
?>

Additionally, it's possible to reset node access statistics of unpublished articles with each cron run.

<?php
/**
 * Reset counts of unpublished nodes.
 * Implements hook_cron().
 */
function YOUR_MODULE_cron() {
  if (
variable_get('statistics_count_content_views', 0)) {
   
// Reset counts of unpublished nodes.

   
$unpblished = db_select('node', 'n')
      ->
condition('n.status', 0, '=')
      ->
fields('n', array('nid'));

   
db_update('node_counter')
      ->
fields(array('daycount' => 0, 'totalcount' => 0))
      ->
condition('nid', $unpblished, 'IN')
      ->
execute();

   
watchdog('ibexutils', 'Reset counts of unpublished nodes.', array());
  }
}
?>