在当前主题的functions.php文件里添加以下代码:
/*
统计文章浏览次数
*/
function yundanran_getPostViews($postID)
{
$count_key = 'yundanran_post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count=='' || !$count)
{
// delete_post_meta($postID, $count_key);
// add_post_meta($postID, $count_key, '0');
return "0";
}
return $count;
}
function yundanran_setPostViews($postID)
{
$count_key = 'yundanran_post_views_count';
$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);
}
}
function yundanran_count_view()
{
global $wpdb;
$count=0;
$views= $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key='yundanran_post_views_count'"); //所有阅读次数
foreach($views as $key=>$value)
{
$meta_value=$value->meta_value;
if($meta_value!='')
{
$count+=(int)$meta_value;
}
}
return $count;
}
附:以上代码用到的函数:
get_post_meta();
delete_post_meta();
add_post_meta();
update_post_meta();
$wpdb->get_results($sql);
主题调用显示:
首页文章调用:在首页文章的循环里添加以下调用代码显示阅读次数:
文章页面single.php或自定义页面添加调用代码
整站文章阅读次数统计调用代码
效果参考本站标题下边右上角的的日志浏览总数统计。
- 我的微信
- 这是我的微信扫一扫
-
- 我的微信公众号
- 我的微信公众号扫一扫
-