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');"); 

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

  • Where are you calling this code? You might accidentally be inside a loop that contains multiple posts. What's the context here? – EAMann Jul 13 '12 at 16:48
  • It's hooked into 'wp_head' - is there a better way to execute this function so the DB is updated? Thanks – dkmojo Jul 13 '12 at 18:16
  • I left out my if statement, just added it to the code. – dkmojo Jul 13 '12 at 18:28

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.

$location = $_SERVER[‘DOCUMENT_ROOT’];

include ( $location . '/wp-config.php' );
include ( $location . '/wp-load.php' );

global $wpdb;
$contactus_table = $wpdb->prefix."user";
if( isset( $_POST['submit'] ) ) {   

    $sql = "INSERT INTO $contactus_table        

    if( $wpdb->query( $sql ) ) {
        echo "data is inserted";
  • 3
    Answers should be more than a code snippet. Please file an edit and explain why this would work. – Gabriel Aug 18 '15 at 20:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.