Wordpress insert query runs 3 times

2019-08-31 23:31发布

I made the following function to track the views of a Wordpress post or page. The strange thing is that the insert query runs three times instead of one.

I tried to resolve this with the following action hook, but without result so far.

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

My code:

add_action('wp_footer',function(){
    global $wpdb;
    global $wp_query;

    $post_id  = $wp_query->post->ID; 
    $count    ='1';
    $datetime = date("Y-m-d H:i:s");   

    $sql = $wpdb->prepare("INSERT IGNORE INTO track_views (datetime, count, post_id) 
                     VALUES (%s, %d, %d) 
                     ON DUPLICATE KEY UPDATE count = count +1", 
                    $datetime, $count, $post_id);
        $wpdb->query($sql);

});

Update: If I go from page X to page Y it seems to count both pages instead of only the current page. How to only count the current page?

3条回答
Bombasti
2楼-- · 2019-08-31 23:48

I had the exact same problem... It was the Yoast SEO plugin.

I disabled all plugins (except Exec-PHP, v4.9) and the code ran fine. After testing all 11 other plugins separately on a clean install of WP - JUST the Yoast SEO plugin + Exec-PHP plugin enabled caused the 3 record phenomenon.

DATABASE TABLE STRUCTURE:

CREATE TABLE `dk_test_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `value1` int(11) NOT NULL,
  `value2` int(11) NOT NULL,
  PRIMARY KEY (`id`)
)

WP PAGE CODE (Writes a single record to the custom table):

<?php
global $wpdb;
$wpdb->insert( dk_test_table, array( 'value1' => "1", 'value2' => "2"));
?>

Disabled Yoast SEO plugin, view page, 1 record inserted.
Enabled Yoast SEO plugin, view page, 3 identical records inserted.

WP Version: 4.7.3
Yoast SEO Version: 4.4

I hopes this helps someone out there!

查看更多
老娘就宠你
3楼-- · 2019-08-31 23:57

I don't know if it's the case, but where do you have your "add_action" function? According to this: https://wordpress.stackexchange.com/questions/21941/wp-footer-hook-running-twice, you should have your add_action() call outside the Widget class.

查看更多
Bombasti
4楼-- · 2019-09-01 00:07

My problem was at the expressions breakpoint. I put $wpdb->query in my expression window in Eclipse so it got executed along with the one in the code.

查看更多
登录 后发表回答