- A+
所属分类:WordPress
首先在文章或页面前部分模板声明PostViews函数。
<?php setPostViews(get_the_ID()); ?>
然后在需要展示PostViews的地方添加以下代码。
<?php echo getPostViews(get_the_ID()); ?>
最后在主题functions.php
文件添加函数代码。
<?php
// function to display number of posts.
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.' Views';
}
// function to count views.
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);
}
}
?>
独角兽驿站
公众号