给客户写模板的时候,发现使用WP-PostViews插件不能统计浏览量,在single.php页面中使用了之后显示的浏览次数一直是0,即使别人浏览过了。
在后台的插件列表中找到WP-PostViews,并点击编辑,打开其源代码,找到了如下函数
### Function: Calculate Post Views
add_action('wp_head', 'process_postviews');
function process_postviews() {..}
可以发现这个process_postviews()函数就是统计浏览次数的函数,在这里使用了这样一句代码:
add_action('wp_head', 'process_postviews');
经过在wordpress的帮助文档中找到关于两个函数的说明:
add_action(): http://codex.wordpress.org/Function_Reference/add_action Hooks a function on to a specific action. wp_head(): http://codex.wordpress.org.cn/Plugin_API/Action_Reference/wp_head
ttwp_head()/tt is triggered within the tthead/head/tt section of the user’s template by the ttwp_head()/tt function. Although this is theme-dependent, it is one of the most essential theme hooks, so it is fairly widely supported.
知道了,这句代码是在wp_head执行时添加自定义的一些动作,这里就是添加了这个统计访问数的函数process_postviews(),为了让这句话能够被执行,需要在wordpress主题程序中添加上wp_head()这个函数,以便能够执行到被添加的process_postviews()函数。
所以解决的方法就是在header.php文件中的
这样就可以正常统计浏览量了,与之类似的函数还有wp_footer()。
感谢原出处:http://www.itzhai.com/use-wp-postviews-plug-statistics-not-page-views.html
WP-PostViews 显示一直是0怎么办?
先检查主题的 header.php 是否在 head 标签内调用了 wp_head()。WP-PostViews 的统计函数是挂在这个钩子上的,主题不触发它,插件就不会执行计数。补上后刷新页面再测试,通常就能恢复正常。
为什么装了插件浏览量还是不变?
因为插件并不是独立后台轮询统计,而是依赖主题页面加载时触发钩子执行。若模板缺少 wp_head(),process_postviews() 就不会运行,所以前台看起来像“失效”了。
除了wp_head还有类似的地方吗?
有,文中提到 wp_footer() 也是常见的主题钩子。很多功能型代码都依赖这些位置被调用,做 WordPress 模板时要确认主题文件把对应钩子放对位置,否则插件和自定义功能都可能不生效。







发表回复