作为WordPress使用者,能不使用插件就尽量不安装插件,作为WordPress主题制作者,就更不应该让主题依赖插件了。文章阅读计数和热门文章列表是常见的需求,实现起来其实也并不复杂。
设置文章阅读数量函数:
- function bzg_set_post_views() {
- global $post;
- if( ! isset( $post->ID ) || ! is_singular() ) return;
- $cookie_name = 'views_' . $post->ID;
- if( isset( $_COOKIE[$cookie_name] ) ) return;
- $post_views = (int) get_post_meta( $post->ID, 'views', true );
- if( empty( $post_views ) ) {
- $post_views = 1;
- } else {
- $post_views = $post_views + 1;
- }
- update_post_meta( $post->ID, 'views', $post_views );
- setcookie( $cookie_name, 'yes', ( current_time( 'timestamp' ) + 86400 ) );
- }
- add_action( 'get_header', 'bzg_set_post_views' );
代码中86400是指同一浏览器访问24小时内不计数,这样就能一定程度上避免刷阅读数。
读取文章阅读数量函数:
- function bzg_post_views($post_ID = '') {
- global $post;
- $post_id = $post_ID;
- if( ! $post_id ) $post_id = $post->ID;
- if( ! $post_id ) return;
- $post_views = (int) get_post_meta( $post_id, 'views', true );
- if( empty( $post_views ) ) $post_views = 0;
- return $post_views;
- }
以上代码放到主题文件functions.php中,在需要显示文章阅读数的地方调用:
- <?php echo bzg_post_views(); ?>
获取阅读数最多的文章:
- function bzg_get_most_viewed( $limit = 10 ) {
- $args = array(
- 'posts_per_page' => $limit,
- 'order' => 'DESC',
- 'post_status' => 'publish',
- 'orderby' => 'meta_value_num',
- 'meta_key' => 'views',
- 'date_query' => array(
- array(
- 'after' => '-360day',
- )
- ),
- );
- $str = implode('&', $args);
- $postlist = wp_cache_get('hot_post_' . md5($str), 'beizigen');
- if(false === $postlist) {
- $postlist = get_posts( $args );
- wp_cache_set('hot_post_' . md5($str), $postlist, 'beizigen', 86400);
- }
- foreach ( $postlist as $post ) {
- echo '<li><a href="' . get_permalink($post->ID) . '" rel="bookmark">' . $post->post_title . '</a></li>';
- }
- wp_reset_postdata();
- }
注意函数中的-360day,是指输出360天内的文章,函数调用方法:
- <ul>
- <?php bzg_get_most_viewed(8); ?>
- </ul>