1

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.