我实际上没有任何代码,但我正在尝试获取WordPress站点上每个页面的页面视图(每次我点击刷新,页面视图的数量应该会增加)。我也希望这样,我可以将不断增加的数字输出到dashboard widget. 我可以想象有点复杂的代码,但我不知道从哪里开始。
如何获取站点上每个页面浏览量,并将(增加的)浏览量添加到Dashboard Widget
2 个回复
SO网友:Robert hue
您可以在不使用任何插件的情况下生成页面视图计数。您需要做的是为每个帖子创建一个帖子元键(当然是自动的),并在每次帖子/页面加载或访问时增加该帖子元键的计数器。
下面是创建post元键的函数post_views_count
对于每个帖子,在每个页面/帖子加载上调用此函数将使帖子数量增加1。
// Post views function
function wps_set_post_views( $postID ) {
$count_key = \'post_views_count\';
$count = get_post_meta( $postID, $count_key, true );
if ( $count==\'\' ){
$count = 0;
delete_post_meta( $postID, $count_key );
add_post_meta( $postID, $count_key, \'0\' );
} else {
$count++;
update_post_meta( $postID, $count_key, $count );
}
}
现在需要从调用此函数single.php
和page.php
. 把这个贴在这些页面上。如果您使用W3 Total Cache 或者类似的缓存插件,然后您需要使用片段缓存来确保在每次页面加载时调用该函数。<?php wps_post_views( get_the_ID() ); ?>
这将设置您的帖子/页面浏览量,并在每次访问时增加一个计数器。现在,如果您想在admin列上添加帖子视图,那么您可以像这样为帖子视图添加一列。
// Get post views
function wps_get_post_views( $postID ) {
$count_key = \'post_views_count\';
$count = get_post_meta( $postID, $count_key, true );
if ( $count==\'\' ){
delete_post_meta( $postID, $count_key );
add_post_meta( $postID, $count_key, \'0\' );
return "0 View";
}
return $count.\' Views\';
}
// Add to admin post column
add_filter( \'manage_posts_columns\', \'posts_column_views\' );
add_action( \'manage_posts_custom_column\', \'posts_custom_column_views\', 5, 2 );
function posts_column_views( $defaults ) {
$defaults[\'post_views\'] = __(\'Views\');
return $defaults;
}
function posts_custom_column_views( $column_name, $id ){
if ( $column_name === \'post_views\' ) {
echo wps_get_post_views( get_the_ID() );
}
}
就是这样。所有这些函数都将放入函数中。php文件,代码除外single.php
和page.php
调用函数设置后期视图。SO网友:Mayeenul Islam
有许多插件显示了该网站的统计数据以及热门帖子/页面的阅读量。
- Jetpack by WordPress.com - 有一个很好的站点统计模块,还有其他模块。。。
结束