A few months ago I added a simple post view counter that adds a count to the post meta every time the footer loads. I refresh the page, and the count goes up by one. It’s simple and it works as expected. One post is over 20k views since November. However, Google Analytics is only showing just over 1700 views, and they were both implemented prior to the post being made. This is not unique views, it is the total views. Unique views (according to Google) is 1600-ish. So my question is: am I doing something wrong that would be causing my post to load multiple times? Or is Google Analytics filtering things out? Google also shows me when bots hit, so I’m thinking it’s something with my code.
/**
* Count every time someone views a post
*/
function eri_count_post_views() {
if ((is_single() || is_page()) && !eri_has_role('administrator')){
$post_id = get_the_ID();
$meta_key = 'eri_post_view_count';
$count = 0;
if (get_post_meta( $post_id, $meta_key, true ) && get_post_meta( $post_id, $meta_key, true ) != '') {
$count = get_post_meta( $post_id, $meta_key, true );
}
$count++;
update_post_meta( $post_id, $meta_key, $count );
// Update the post with the last viewed date/time
$timezone = wp_timezone_string();
date_default_timezone_set($timezone);
$now = date('Y-m-d H:i:s');
update_post_meta( $post_id, 'eri_post_last_viewed', $now );
}
}
add_action('wp_footer', 'eri_count_post_views');