首先需要了解几个Wordpress内置函数。PHP内置setcookie()函数,其参数使用如下:
/* ---------------------------------
@param name: 规定 cookie 的名称, 必须;
@param value:规定 cookie 的值,必须;
@param expire:规定 cookie 的过期时间, 可选;
@param path: 规定 cookie 的服务器路径,可选;
@param domain: 规定 cookie 的域名,可选;
@param secure: 是否需要选用HTTPS传输cookie,可选;
--------------------------------- */
// PHP setcookie()
setcookie(name,value,expire,path,domain,secure)
关于expire参数,时间单位为秒,time()+3600 将设置 cookie 的过期时间为 1小时。如果这个参数没有设置,那么 cookie 将在 session 结束后(即浏览器关闭时)自动失效。
WordPress框架wp-includes/post.php目录下的get_post_meta()函数:
/* ---------------------------------
@param $post_id:
(string) (Required) Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user', or any other object type with an associated meta table;
@param $key = '':
(string) (Optional) The meta key to retrieve. By default, returns data for all keys;
Default value: ''
@param $single:
(bool) (Optional) If true, returns only the first value for the specified meta key. This parameter has no effect if $key is not specified.
Default value: false
--------------------------------- */
// WordPress get_post_meta()
function get_post_meta( $post_id, $key = '', $single = false ) {
return get_metadata( 'post', $post_id, $key, $single );
}
应用get_post_meta(),我们可以在构建如下两个函数,以设置及返回文章阅读量,函数可挂载在theme的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);
}
}
随后应用setcookie()函数,在文章显示页single.php调用已构建的计数函数:
<?php
if(!isset($_COOKIE['views'.$post->ID.COOKIEHASH]) || $_COOKIE['views'.$post->ID.COOKIEHASH] != '1'){
setPostViews($post->ID);
setcookie('views'.$post->ID.COOKIEHASH,'1',time() + 3600,COOKIEPATH,COOKIE_DOMAIN);
}
?>
最后挂载应用返回函数getPostViews()来获得文章访问量信息:
<?php echo getPostViews(get_the_ID()); ?>