WordPress 文章浏览次数与点击排行榜的例子
我们在很多个人站长博客中会看到有一些网站的浏览排行了,那么这种功能要如何来实现呢,下面小编就同各位介绍一下吧.
在一小时内刷新文章不会多次统计,只会被算作一次访问,把下面的代码复制粘贴到主题的 functions.php 里面:
-
- function record_visitors(){
- if (is_singular()) {
- global $post;
- $post_ID = $post->ID;
- if($post_ID) {
- if(isset($_COOKIE['views'.$post_id.COOKIEHASH]) && $_COOKIE['views'.$post_id.COOKIEHASH] == ’1′)return;
- $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);
- }
- setcookie(‘views’.$post_id.COOKIEHASH,’1′,time() + 3600,COOKIEPATH,COOKIE_DOMAIN);
- }}}
- add_action(‘wp_head’, ‘record_visitors’);
- 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;
- }
在需要的位置用下面的代码调用,代码如下:
<?php if (function_exists(‘post_views’)) post_views(); ?>
然后是浏览次数排行榜,参考了WP-Postviews 插件源代码,可以设置限定近期一段时间内的文章的浏览次数排行,更为实用,所以这个相当不错的插件真的可以丢掉了.
添加到 functions.php 里,代码如下:
-
- function most_viewed($limit = 10) {
- global $wpdb, $post;
- $output = ”;
- $most_viewed = $wpdb->get_results(“SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date > ‘” . date(‘Y-m-d’, strtotime(‘-100 days’)) . “‘ AND post_type =’post’ AND post_status = ‘publish’ AND meta_key = ‘views’ AND post_password = ” ORDER BY views DESC LIMIT $limit”);
- if($most_viewed) {
- foreach ($most_viewed as $post) {
- $output .= “\n<li><a href= \”".get_permalink($post->ID).”\” rel=\”bookmark\” title=\”".$post->post_title.” (“.$post->views.”+)\” >”. $post->post_title.” (“.$post->views.”+)</a></li>”;
- }
- echo $output;
- }}
在页面适当的地方调用代码如下,括号内参数为显示数目,代码如下:
<?php if (function_exists(‘most_viewed’)) most_viewed(10); ?>