本页目录
在大部分网站中,在文章页的顶部方式浏览次数统计,是很多博客或者网站常用的展示方法,通过这个数据,访客可以判断这篇文章受欢迎的程度,站长也可以通过这个数据来分析自己的文章质量。
- 代码来源:详情
代码部署
在主题根目录下的 functions.php 文件中的<?php 下添加以下代码并保存。
/*---------------------------------------------------------------------- * * WordPress 功能 >>>> 开启访问统计 * * @Description: 前端开启访问、后台展示 *------------------------------------------------------------------------*/
add_action('wp_head', '_post_views_record');
//增加文章访问量function _post_views_record(){ if (is_singular()) { global $post; $post_ID = $post->ID; if ($post_ID) { $post_views = (int) get_post_meta($post_ID, 'views', true); if (!update_post_meta($post_ID, 'views', ($post_views + 1))) { add_post_meta($post_ID, 'views', 1, true); } } }}
//前端调用function _get_post_views(){ global $post; $post_ID = $post->ID; $views = (int) get_post_meta($post_ID, 'views', true); return $views;}
//后台展示访问数量if(!function_exists('AddViewsColumn')){
function AddViewsColumn($cols){ $cols['views'] = __('阅读'); return $cols; }
function GetViewsValue($column_name, $post_id){ $views = (int) get_post_meta($post_id, 'views', true); echo $views; }
// for posts add_filter('manage_posts_columns', 'AddViewsColumn'); add_action('manage_posts_custom_column', 'GetViewsValue', 10, 2);
// for pages add_filter('manage_pages_columns', 'AddViewsColumn'); add_action('manage_pages_custom_column', 'GetViewsValue', 10, 2);
}前端调用
<?php //浏览计数 echo _get_post_views();?>效果预览

