在一小时内刷新文章不会多次统计,只会被算作一次访问,把下面的代码复制粘贴到主题的 functions.php 里面:
代码如下 | 复制代码 |
/***** Postviews *****/ 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 里
代码如下 | 复制代码 |
/***** Most Viewed *****/ 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”);//设置近100天内文章的排行榜 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); ?> |
时间: 2024-10-31 09:13:17