WordPress query runs twice

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();
    });

Related posts

Leave a Reply

1 comment