众所周知,对于 WordPress
的批评是插件越多越慢(其实在我看来并不是插件越多,而是越慢越多对查询和事件的钩子),所以我写了一个纯代码版本,实现了读取统计和部分查询功能。
当然,也许你想说这些已经被别人分享过了;是的,在我写之前,我肯定会去网上看看现有的,发现有一些不尽人意的地方,比如添加 meta
的钩子放在 wp_head
上,查询阅读量必须通过 post_id
等。
/**
* 判断阅读数量是否需要增加并进行操作
* 转载请注明来自:https
://licoy
.cn
/3462.html
*/
function
the_views_add
($post_ID
,$count
,$key
){
if
(is_single
() || is_page
()) {
if
($count
== '') {
add_post_meta
($post_ID
, $key
, '0');
} else
{
update_post_meta
($post_ID
, $key
, $count
+ 1);
$count
++;
}
}
return
$count
;
}
//获取当前的阅读数量与自增
function
the_views
($post_id
=null
,$echo
=true
) {
global
$post
;
if
($post_id
==null
){
$post_id
= $post
->ID
;
}
$key
= 'views
';
$count
= get_post_meta
($post_id
, $key
, true
);
if
($count
== '') {
$count
= 0;
}
$count
= the_views_add
($post_id
, $count
, $key
);
$count
= number_format_i18n
($count
);
if
(!$echo
){
return
$count
;
}
echo
$count
;
}
//设置文章发布的时候进行字段添加
function
set_views
($post_ID
) {
$key
= 'views
';
$count
= get_post_meta
($post_ID
, $key
, true
);
if
($count
== '') {
add_post_meta
($post_ID
, $key
, '0');
}
}
add_action
('publish_post
', 'set_views
');
这里再分享一个查询函数,因为是自定义的所以就没有插件的附带函数支持,这个函数是查询 N
天内阅读数量最多的文章:
/**
* 转载请注明来自:https
://licoy
.cn
/3462.html
* 获取查看最多的文章
* @param
$days
N
天内
* @param
$nums
数量
* @return
array
|object
|null
*/
function
get_views_most_post
($days
, $nums
){
global
$wpdb
;
$sql
= ;
return
$wpdb
->get_results
($sql
);
}
在此汇站网希望大家能喜欢。
转载请注明:汇站网 » WordPress
纯代码实现阅读量统计