我们有时候在做公司客户网站的时候找到的成品或者半成品主题有的是有自带浏览阅读次数的,有些是不带的,省事的办法直接安装阅读次数插件可以快速实现。有些时候不着急赶工,可以寻找几个免插件的实现方法,这里也把我这几天在调整的主题可以实现免插件实现阅读次数的展示方法记录下来。
首先打开functions.php文件,把以下代码放在末端
/** 阅读数 */
function get_post_views ($post_id) {
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
$count = '0';
}
echo number_format_i18n($count);
}
function set_post_views () {
global $post;
$post_id = $post -> ID;
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if (is_single() || is_page()) {
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
} else {
update_post_meta($post_id, $count_key, $count + 1);
}
}
}
add_action('get_header', 'set_post_views');
然后找到你需要调用的文章页模板位置添加调用代码,调用代码如下:
<?php get_post_views($post -> ID); ?>
这样就能展示出浏览量了。