给WordPress文章添加统计代码,需要安装WP-Postviews这个插件进行设置
这里分享一个使用非插件的方式为文章增加阅读统计,进入WP后台—外观—主题编辑器,打开函数模板(functions.php)这个文件,将下边的代码添加进去。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| 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');
|
接下来在需要显示阅读次数的地方插入下面的代码,即可实现效果。一般需要添加的文件有 首页模板(index.php)、文章页面(single.php)、文章归档(archive.php)
1
| <?php get_post_views($post -> ID); ?> 次阅读
|
原文地址:https://www.xiaoyi.vc/wordpress-post-views.html