大家都习惯使用 WP-Postviews 这款插件来统计文章浏览数,这个插件附带了很多统计输出函数,其实大部分人也就只要统计下浏览数,然后显示出来就行,以下是 zww 精简版。
主体函数代码
把下面代码放入主题的 functions.php 里面( 里面)
/*
postviews
Origin: http://of.gs/un-plugin-post-views.html
Modify: zwwooooo https://zww.me
Version:0.2.0
*/
function custom_the_views($post_id, $echo=true, $unit=' views') {
$count_key = 'views';
$views = get_post_custom($post_id);
$views = intval($views['views'][0]);
if ($views == '') {
return '';
} else {
if ($echo) {
echo number_format_i18n($views) . $unit;
} else {
return number_format_i18n($views) . $unit;
}
}
}
function set_post_views() {
global $post;
$post_id = intval($post->ID);
$count_key = 'views';
$views = get_post_custom($post_id);
$views = intval($views['views'][0]);
if (is_single() || is_page()) {
if(!update_post_meta($post_id, 'views', ($views + 1))) {
add_post_meta($post_id, 'views', 1, true);
}
}
}
add_action('get_header', 'set_post_views');
使用方法
浏览数显示函数:custom_the_views($post_id, $echo=true, $views=' views')
参数说明
1. $post_id: 文章ID,一般填 $post->ID 2. $echo: true/false,显示/获取浏览数(默认是显示-true) 3. $views: 浏览数单位(默认是:空格+views)
一般调用方法:
<?php if ( function_exists('custom_the_views') ) custom_the_views($post->ID); ?>
Comments:0