I made the following function to track the views of a Wordpress post or page. The strange thing is that the insert query runs three times instead of one.
I tried to resolve this with the following action hook, but without result so far.
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
My code:
add_action('wp_footer',function(){
global $wpdb;
global $wp_query;
$post_id = $wp_query->post->ID;
$count ='1';
$datetime = date("Y-m-d H:i:s");
$sql = $wpdb->prepare("INSERT IGNORE INTO track_views (datetime, count, post_id)
VALUES (%s, %d, %d)
ON DUPLICATE KEY UPDATE count = count +1",
$datetime, $count, $post_id);
$wpdb->query($sql);
});
Update: If I go from page X to page Y it seems to count both pages instead of only the current page. How to only count the current page?
I had the exact same problem... It was the Yoast SEO plugin.
I disabled all plugins (except Exec-PHP, v4.9) and the code ran fine. After testing all 11 other plugins separately on a clean install of WP - JUST the Yoast SEO plugin + Exec-PHP plugin enabled caused the 3 record phenomenon.
DATABASE TABLE STRUCTURE:
WP PAGE CODE (Writes a single record to the custom table):
Disabled Yoast SEO plugin, view page, 1 record inserted.
Enabled Yoast SEO plugin, view page, 3 identical records inserted.
WP Version: 4.7.3
Yoast SEO Version: 4.4
I hopes this helps someone out there!
I don't know if it's the case, but where do you have your "add_action" function? According to this: https://wordpress.stackexchange.com/questions/21941/wp-footer-hook-running-twice, you should have your add_action() call outside the Widget class.
My problem was at the expressions breakpoint. I put $wpdb->query in my expression window in Eclipse so it got executed along with the one in the code.