Insert query inserts 2 entries, should insert 1

I’ve written a small posts by views plugin, well at least started one.

My tables are set up but when they are updated the code adds 2 entries into my table when a post is loaded and views are tracked. I literally have no idea why this is happening. It looks like the second post id entered into the DB table is the post directly after the one that is loaded. Example: if the post being viewed has id = 121, the code adds post 121 and 124.

Here’s my insert code:

if( is_single() && !is_page() ):
    // add a new data row into the views DB table with the post ID         
    $wpdb->query("INSERT INTO {$ppbv} (post_id, post_type) VALUES ('{$post->ID}','{$post->post_type}');"); 

    $data = $wpdb->get_row("SELECT * FROM {$ppbv_total} WHERE post_id='{$post->ID}'", ARRAY_A); // get the data row that has the matching post ID       

    if(!is_null($data)): // if we have a matching data row  
        $new_views = $data['views'] + 1; // increase the views by 1
        // update the data row with the new views
        $wpdb->query("UPDATE {$ppbv_total} SET views="{$new_views}" WHERE post_id='{$post->ID}';");           
    else: // if we don't have a matching data row (nobody's viewed the post yet)
        // add a new data row into the DB with the post ID and 1 view  
        $wpdb->query("INSERT INTO {$ppbv_total} (post_id, post_type, views) VALUES ('{$post->ID}','{$post->post_type}','1');"); 
    endif;
endif;

If anyone could shed some light on this I would greatly appreciate it!

2 Answers
2

Sounds like browser prefetching, see WordPress core tickets #12603, #14382, and #20192.

Basically, sometimes some browsers see what the next post is, and decide to go ahead and load it while you are reading this one. So when you go to the next post it loads immediately, instead of you having to wait. The downside, as you found in this case, is that sometimes this has unexpected side affects if the user doesn’t end up viewing the other post.

Leave a Comment