Citizen SP
Citizen SP

Reputation: 1411

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

Upvotes: 1

Views: 1006

Answers (1)

henrywright
henrywright

Reputation: 10240

Sometimes pre-fetching can add extra views. Add this to your theme's functions.php file to see if it resolves the problem:

remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );

See here for more info: https://core.trac.wordpress.org/ticket/14568

Upvotes: 4

Related Questions