wp/wordpress文章页面添加阅读量/点击量,后台并显示阅读量
七娃博客1,161人阅读
我们知道wp主题默认的是不带阅读量这个字段的,所以要想在前端文章页面显示阅读量以及后台文章列表显示阅读量,就需要我们修改functions.php这个文件,接下来分享一下我整理的wp添加阅读量的代码。
1.前端页面添加阅读量/点击量
在functions.php加入
function record_visitors(){ if (is_singular()){ global $post; $post_ID = $post->ID; if($post_ID){ $post_views = (int)get_post_meta($post_ID, 'views', true); if(!update_post_meta($post_ID, 'views', ($post_views+1))){ add_post_meta($post_ID, 'views', 1, true); } } } } add_action('wp_head', 'record_visitors'); function post_views($before = '(点击 ', $after = ' 次)', $echo = 1){ global $post; $post_ID = $post->ID; $views = (int)get_post_meta($post_ID, 'views', true); if ($echo) echo $before, number_format($views), $after; else return $views; }
在需要的地方,加入:
<?php post_views(' ', ' 次'); ?>
2.后台列表显示每篇文章的阅读量
在functons.php添加:
//在后台文章列表增加一列数据 add_filter( 'manage_posts_columns', 'customer_posts_columns' ); function customer_posts_columns( $columns ) { $columns['views'] = '浏览次数'; return $columns; } //输出浏览次数 add_action('manage_posts_custom_column', 'customer_columns_value', 10, 2); function customer_columns_value($column, $post_id){ if($column=='views'){ $count = get_post_meta($post_id, 'views', true); if(!$count){ $count = 0; } echo $count; } return; }
效果如下:
评论 | 0 条评论
登录之后才可留言,前往登录