相信不少门户都是用wordpress搭建的,那么我们在不使用插件的情况下如何简单地实现文章阅读次数的统计呢?下面有两个方法可供参考:
方法一:
1、首先打开我们的后台控制面板,点击外观——编辑
2、在右栏找到函数模板function.php
在文件的最末尾添加如下代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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);
}
}
|
添加之后记得更新文件
3、然后我们打开文章页面single.php,找到与下面类似的地方
1
|
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
|
在它的下面添加如下代码
1
|
<?php setPostViews(get_the_ID()); ?>
|
最后将我们需要展示阅读次数的地方添加如下代码
1
|
<?php echo getPostViews(get_the_ID()); ?>
|
方法二:
1、和方法一一样,找到function.php添加如下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
function get_post_views ($post_id) {
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
$count = '0';
}
echo number_format_i18n($count);
}
function set_post_views () {
global $post;
$post_id = $post -> ID;
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if (is_single() || is_page()) {
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
} else {
update_post_meta($post_id, $count_key, $count + 1);
}
}
}
add_action('get_header', 'set_post_views');
|
然后在文章页面single.php的需要显示的位置添加如下代码
1
|
阅读次数 <?php get_post_views($post -> ID); ?>
|
注意:如果部分博主使用的主题是特殊的主题,那么文章页面应该是loop-single.php,把上面方法里面的single.php替换成loop-single.php即可
- 赞助本站
- 微信扫一扫
-
- 加入Q群
- QQ扫一扫
-
评论