纯代码统计文章浏览次数
1.在主题的 functions.php文件的最后一个 ?> 前面添加下面的代码:
| 代码如下 | 复制代码 |
| function record_visitors() { 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); } } } } add_action('wp_head', 'record_visitors'); /// 函数名称:post_views /// 函数作用:取得文章的阅读次数 function post_views($before = '(点击 ', $after = ' 次)', $echo = 1) { global $post; $post_ID = $post->ID; $views = (int)get_post_meta($post_ID, 'views', true); if ($echo) echo $before, number_format($views), $after; else return $views; } | |
2.在需要显示该统计次数的地方使用下面的代码调用:
文章被阅读:<?php post_views(' ', ' 次'); ?>
获取浏览次数最多的文章
这个一般来说,就是用来获得热门文章了.如果要获取上面的函数统计出来的浏览次数最多的文章,可以在 functions.php文件的最后一个 ?> 前面添加下面的代码:
| 代码如下 | 复制代码 |
|
/// 函数作用:取得阅读最多的文章 if ($show_date) { $posted = date(get_option('date_format'), strtotime($viewed->post_date)); $output .= "$beforedate $posted $afterdate"; } $output .= "$beforecount $post_views $aftercount"; } } else { $output = "N/An"; } echo $output; } | |
然后使用下面的函数调用:
| 代码如下 | 复制代码 |
|
<?php get_most_viewed_format(); ?> | |
小结
这里部落需要补充一下的是,用上面的方法获得的文章浏览次数统计,与WP-Postviews 插件是有所差别的,这里的代码获取的,其实就连搜索引擎爬虫也会进行统计.
5大ai写作生成器推荐,让创作变得更简单有哪些-类型差异和选择建议
TPLink TLH28RD 无线路由器无线(WiFi)设置方法
如何轻松制作部门年终总结PPT怎么做-执行顺序和关键限制
部门工作总结PPT如何处理写?一份详细的范文与提示词助你轻松搞定讲了什么-主要信息和内容重点
如何选择ai写作软件哪个好,WPS AI助力文档创作效率与质量讲了什么-主要信息和内容重点
轻松打开AI格式文件,四种简便处理思路助你快速解决问题讲了什么-主要信息和内容重点