WordPress纯代码实现文章点击数的实现放发,两种方式
第一方法,每次刷新数字增加一次
第一步:将以下代码加到函数文件functions.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 View”;
}
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);
}
}
第二步:将下面的代码到主题的 single.php 的文章的 loop 里:也就是文章内容调用那个位置!
<?php setPostViews(get_the_ID()); ?>
第三步:将下面的代码拷贝到任意你的主题模板里想要显示点击数的地方
<?php echo getPostViews(get_the_ID()); ?>
第二种方法页面刷新一次增加一次点击
以上这种每次刷新会增加一个点击,另一种方式,刷新页面不累计,稍微做一下修改。
第一步:将下面代码放到函数文件中
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的最上端(这个和上有区别)
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);
}
第三步:将下面的代码拷贝到任意你的主题模板里想要显示点击数的地方(和上面一样)
<?php echo getPostViews(get_the_ID()); ?>
问题本身还是很简单的,只是对于不熟悉的网友来说不知道什么原因,如果英语不太好的话,就以为自己买了个假主题了。问题本身还是很简单的,只是对于不熟悉的网友来说不知道什么原因,如果英语不太好的话,就以为自己买了个假主题了。