统计页面浏览次数的插件非常多,但是缺点也有不少,最大的缺点就是插件装多了网页打开会变慢,其次就是此类插件通常会多出很多我们不需要的功能,这个时候用代码来实现这个功能是最合适的不过的。
首先把下面这段代码放在functions.php中
// function to display number of posts.
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}// function to count views.
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
然后把下段代码放在single.php中,并确保把代码贴在循环(loop)里。
<?php setPostViews(get_the_ID()); ?>
最后一步,你想在哪里显示计数就在哪里加上下面这段代码
<?php echo getPostViews(get_the_ID()); ?>
如果你想在admin面板中也看到统计,就在functions.php中添加如下代码,创建一个查看功能
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
$defaults['post_views'] = __('Views');
return $defaults;
}
function posts_custom_column_views($column_name, $id){
if($column_name === 'post_views'){
echo getPostViews(get_the_ID());
}
}
分类:新闻资讯