Wordpress 插入查询运行 3 次 [英] Wordpress insert query runs 3 times
问题描述
我创建了以下函数来跟踪 Wordpress 帖子或页面的浏览量.奇怪的是插入查询运行了 3 次而不是一次.
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 );
我的代码:
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);
});
更新:如果我从第 X 页转到第 Y 页,它似乎计算两个页面,而不是仅计算当前页面.如何只统计当前页面?
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?
推荐答案
我不知道是不是这样,但是你的add_action"功能在哪里?根据这个:https://wordpress.stackexchange.com/questions/21941/wp-footer-hook-running-twice,您应该在 Widget 类之外调用 add_action().
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.
这篇关于Wordpress 插入查询运行 3 次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!