非插件纯代码实现WordPress增加浏览次数统计及显示评论数

  • 2,671 views
  • 阅读模式
摘要

非插件纯代码实现WordPress增加浏览次数统计及显示评论数

非插件纯代码实现WordPress增加浏览次数统计及显示评论数
wp站点有一段时间了,之前优化了首页加载速度,又感觉缺少浏览次数的统计很不方便,于是便折腾了一下,对浏览次数和评论数做了下优化

统计浏览次数
这个功能做得比较简单,没有做用户及ip去重,只是单纯的统计页面打开次数,将下面代码加入模板的function.php中即可

/**
* 设置阅读次数
* 注意count_key, 后续都是根据这个来统计的
*/
function set_post_views () {
global $post;
$post_id = $post -> ID;
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if (is_single() || is_page()) {
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
} else {
update_post_meta($post_id, $count_key, $count + 1);
}
}
}
add_action('get_header', 'set_post_views');
获取浏览次数
下面函数可以获取浏览次数,在需要显示的地方调用即可

/**
* 阅读次数
* count_key与set函数的count_key一致
*/
function get_post_views ($post_id) {
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
$count = '0';
}
echo number_format_i18n($count);
}
使用示例
最常规的使用应该是文章详情中,一般是文章页面 (single.php)的while ( have_posts() )后面,部分single.php中有get_template_part( 'template-parts/content', 'single');则需要到conent加上下面的代码

ID); ?> 阅读
显示评论次数
在上面浏览次数之后,可以加上评论次数显示

ID); ?> 阅读
 / 

在后台文章列表统计中增加浏览次数
require_once( trailingslashit( get_template_directory() ) . 'trt-customize-pro/newslite/class-customize.php' );

//在后台文章列表增加一列数据
add_filter( 'manage_posts_columns', 'ashuwp_customer_posts_columns' );
/**
* 注意"views"需要与之前统计set方法一致
*/
function ashuwp_customer_posts_columns( $columns ) {
$columns['views'] = '浏览次数';
return $columns;
}

//输出浏览次数
add_action('manage_posts_custom_column', 'ashuwp_customer_columns_value', 10, 2);

/**
* 注意"views"需要与之前统计set方法一致
*/
function ashuwp_customer_columns_value($column, $post_id){
if($column=='views'){
$count = get_post_meta($post_id, 'views', true);
if(!$count){
$count = 0;
}
echo $count;
}
return;
}
原文:简书ThinkinLiu 博客: IT老五

以上代码能实现浏览次数统计,而且免于安装插件。唯一的不好之处是更换主题后,需要重新增加代码(不过历史浏览统计数据不会丢),在这里记录下,以后需要

weinxin
扫码关注微信公众号--IT老五
微信扫一扫关注公众号,获取更多实用app,订阅地址不定时更新
Liu, Thinkin
  • 本文由 发表于 2018-11-23 21:43:45
  • 转载请务必保留本文链接:https://itlao5.com/655.html
评论  0  访客  0
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定