Accurate WordPress post view tracking: Counting unique visitors

Hey folks! I’m trying to set up a view counter for my WordPress blog posts. The tricky part is I want to count each visitor only once per post, not every time they reload the page.

I’ve been messing around with cookies but it’s not quite right. Here’s a snippet of what I’ve got:

function count_unique_views($post_id) {
  $view_key = 'unique_view_count';
  $current_views = get_post_meta($post_id, $view_key, true);
  
  if (!isset($_COOKIE['viewed_' . $post_id])) {
    $new_count = empty($current_views) ? 1 : $current_views + 1;
    update_post_meta($post_id, $view_key, $new_count);
    setcookie('viewed_' . $post_id, '1', time() + 86400, '/');
  }
  
  return $current_views;
}

It kinda works, but sometimes the count still goes up on refreshes. Any ideas on how to make this more accurate? Or is there a better way to track unique views? Thanks for any help!

hey man, i’ve been there too. have u tried using sessions instead of cookies? they’re usually more reliable for this kinda stuff. also, maybe add a timestamp to ur tracking so u can reset after a certain time. that way if someone comes back a week later, it counts as a new view. just an idea!

I have encountered this issue before and discovered that a mixed approach can enhance accuracy. Instead of relying solely on cookies, I set up a system that assigns a unique cookie to each visitor and simultaneously logs the visitor’s IP address along with the post identifier. This method allows the system to verify whether a view is unique before increasing the count. It helps prevent duplicate counts from simple page reloads while also taking into account when visitors clear their cookies. Remember to include a routine to periodically purge old IP data to comply with privacy requirements.

I’ve dealt with this exact problem on several client sites. Here’s what worked for me:

Use a combination of cookies, IP tracking, and browser fingerprinting. Store a hash of these values in your database along with the post ID and timestamp.

Before incrementing the view count, check if that unique hash exists for the post within the last 24 hours. If not, increment and add the hash.

This approach catches most edge cases like cookie clearing or IP changes. You’ll need to implement some cleanup to remove old entries periodically.

One caveat - be mindful of privacy laws if you’re storing any identifiable info. Make sure your privacy policy covers this usage.

Hope that helps! Let me know if you need any clarification on implementation details.