教程前言:
每次进入文章详情页,都会通过 cookie
判断用户是否在设定的到期时间内访问过文章。如果没有,浏览次数将增加一次。
实现过程如下:
1.将以下代码添加到主题的 functions
.php
文件中,并将其放在文件的底部:
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
);
}
}
2.添加以下代码至主题的 single
.php
文件, 时间间隔可自定义设置, 放在该文件最上面即可:
3. 将以下代码添加到要显示浏览次数的位置, 例如 文章列表(template
-parts
/content
.php
), 文章详情页面(template
-parts
/content
-single
.php
), 搜索结果页面(template
-parts
/content
-search
.php
)等。
转载请注明:汇站网 » WordPress
代码实现文章阅读统计和显示(刷新页面不累计)