代码实现WordPress文章浏览次数统计功能

这个功能非常实用,相信很多博客都会用到,今天说一下如何用代码来实现这一功能,当然你也可以使用这个插件来实现同样的功能:

WP-PostViews 1:

在你使用的博客主题里面,找到function.php,加入以下两段代码(加到最后就好):

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 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); } }

2:打开single.php,找到以下代码:

1 <?php the_tags('', ', ', ' / '); ?> &nbsp;

在这段代码后面追加以下代码:

1 <?php setPostViews(get_the_ID()); ?> <?php echo getPostViews(get_the_ID()); ?>

或者,只要在循环体开始后的任何位置加上以上代码都可以。 打开想要显示文章浏览次数的页面如:index.php,加上下面这句代码:

<?php echo getPostViews(get_the_ID()); ?>

OK了,现在已经实现了不用插件就可以显示浏览次数的效果了。

WP-PostViews使用方法:《使用wp-postview插件统计文章浏览次数》

原文地址:https://www.cnblogs.com/homg/p/3345004.html