My WordPress plugin contains the following class to measure the views of my WordPress posts.
The code works, but the query inserts 2 records every time. How can I prevent this?
class my_plugin_class {
function insert_into_wpdb()
{
global $wpdb;
$datetime = date("Y-m-d H:i:s");
$post_id = get_the_title();
$ip = $_SERVER['REMOTE_ADDR'];
$sql = $wpdb->prepare("INSERT INTO plugin_db
(datetime, ip, post_id, count)
VALUES (%s, %s, %d, %d)
ON DUPLICATE KEY UPDATE count = count +1",
$datetime, $ip, $post_id, 1);
$wpdb->query($sql);
}
}
add_action('wp_footer',function(){
$var = my_plugin_class;
$var->insert_into_wpdb();
});
Sometimes pre-fetching can add extra views. Add this to your theme’s functions.php file to see if it resolves the problem:
See here for more info: https://core.trac.wordpress.org/ticket/14568