在 function.php 适当位置插入这段代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function getPostViews($postID){
$count_key = 'views';
$count = get_post_meta($postID, $count_key, true);
if($count=='' || !$count){
return "0";
}
return $count;
}
function setPostViews($postID){
$count_key = 'views';
$count = get_post_meta($postID, $count_key, true);
if($count=='' || !$count) {
$count = 1;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, $count);
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}

在 single.php 最顶上插入这样一段

1
2
3
4
5
6
<?php 
if(!isset($_COOKIE['views'.$post->ID.COOKIEHASH]) || $_COOKIE['views'.$post->ID.COOKIEHASH] != '1'){
setPostViews($post->ID);
setcookie('views'.$post->ID.COOKIEHASH,'1',time() + 99999999,COOKIEPATH,COOKIE_DOMAIN);
}
?>

然后在想插入的地方放这个

1
<p>阅读量: <?php echo getPostViews(get_the_ID());?></p>