无需插件实现wordpress文章浏览次数统计功能

使用wordpress做博客的朋友都知道,在文章统计功能方面,我们只能使用插件来实现,或者修改代码,但是插件太多不利于seo,因此我们可以实现修改代码的方式来实现


1,在functiuons.php的最下面 ?> 之前添加如下代码

/* 访问计数 */
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";
}
return $count;
}
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 );
}
}
2,在需要统计的页面添加如下代码,比如本站是在文章页面添加,既是single.php ,注意,代码需要添加到endwhile之前,也就是循环之中

setPostViews(get_the_ID());
3,在需要显示的地方添加一下代码即可

<?php echo getPostViews(get_the_ID()); ?> 

此外,该代码还有其他的一些功能:

a,显示阅读次数最多的文章或页面:

<?php if (function_exists(‘get_most_viewed’)): ?>
<?php get_most_viewed(); ?>
<?php endif; ?>
b,只显示阅读次数最多的文章:

<?php if (function_exists(‘get_most_viewed’)): ?>
<?php get_most_viewed(‘post’); ?>
<?php endif; ?>
c,只想显示10篇阅读次数最多的文章:

<?php if (function_exists(‘get_most_viewed’)): ?>
<?php get_most_viewed(‘post’,10); ?>
<?php endif; ?>
d,显示显示某类别下的阅读次数最多的文章:

<?php if (function_exists(‘get_most_viewed_category’)): ?>
<?php get_most_viewed_category(the_catagory_ID(false)); ?>
<?php endif; ?>
在get_most_viewed_category函数类别ID决定显示的分类
附<?php get_most_viewed(‘post’,8,0,true,true);?>函数详解:
主题中有这么一句函数,是用来引用“最受欢迎文章”的,后面一共有5个参数可供设置,说明如下:
post:可选post,page,both;
8:控制应用文章的数量;
0:截取文章标题长度,0表示不设置,不设置的话长标题就会自动换行,很难看;
true:显示文章,若改为 false 则不显示文章;
true:不显示搜索引擎机器人的查询次数,若改为 true 则全部显示

当然,如果您觉得设置太过麻烦,那么本站建议您使用使用插件来完成实现

推荐装插件:WP-PostViews


爆款云服务器s6 2核4G 低至0.46/天,具体规则查看活动详情Blog Img