WordPress无插件实现文章浏览量统计方法
在WordPress中实现文章浏览量统计,推荐通过自定义代码方式完成,无需依赖插件,性能更优且便于维护。
通过向主题的functions.php文件添加核心函数,结合模板调用,可实现浏览量统计、格式化显示、排除管理员访问计数,并在后台文章列表中展示浏览量数据。
1. 添加浏览量统计函数
将以下代码添加到当前主题(建议使用子主题)的functions.php文件中:
// 统计文章浏览量function set_post_views($post_id) {$count_key = 'post_views_count';$count = get_post_meta($post_id, $count_key, true);if ($count == '') {$count = 0;delete_post_meta($post_id, $count_key);add_post_meta($post_id, $count_key, '0');} else {$count++;update_post_meta($post_id, $count_key, $count);}}// 获取浏览量并格式化显示function get_post_views($post_id) {$count_key = 'post_views_count';$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');return "0 次查看";}return number_format($count) . ' 次查看';}// 排除管理员访问,仅统计前台用户function track_post_views($post_id) {if (!is_single()) return; // 仅在单篇文章页统计if (empty($post_id)) {global $post;$post_id = $post->ID;}if (!is_admin() && !current_user_can('manage_options')) { // 排除管理员set_post_views($post_id);}}add_action('wp', 'track_post_views');// 后台文章列表显示浏览量列function add_views_column($columns) {$columns['post_views_count'] = '浏览量';return $columns;}add_filter('manage_posts_columns', 'add_views_column');// 后台列中输出浏览量数据function display_views_column($column, $post_id) {if ($column == 'post_views_count') {echo get_post_views($post_id);}}add_action('manage_posts_custom_column', 'display_views_column', 10, 2);
2. 前台调用显示浏览量
在文章模板文件(如single.php或content-single.php)中合适位置(例如标题下方或文章末尾)插入以下PHP代码,即可显示当前文章浏览量:
<?php echo get_post_views(get_the_ID()); ?>

