一个网站比较基本的元素,点击率就是比较常见的要求,通过文章点击的统计来分析网站哪些文章比较受欢迎,从而吸引用户注意到这部分优秀的文章。
WordPress默认是没有加入点击次数的,你可以通过添加一个插件叫post-view-plus等相关插件来使其支持输出点击次数、热门点击文章小工具等。本文介绍的是另外一种方式,通过添加一个自定义字段view到function.php中来实现点击次数统计和输出热门点击文章。
//Post View From qdkfweb.cn 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(' ', ''); ?>
在侧栏添加你的热门点击文章代码:
<ul> <?php //Popular Post Form qdkfweb.cn $args = array( 'posts_per_page' => 5,//文章数 'meta_key' => 'views', 'orderby' => 'meta_value_num', 'date_query' => array( array( 'after' => '2 month ago',//时间范围 )) ); $postslist = get_posts( $args ); foreach ( $postslist as $post ) : setup_postdata( $post ); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </li> <?php endforeach; wp_reset_postdata(); ?> </ul>
还有另外一个通过MySQL查询的函数。
/* * 热门点击文章 * “一个月内”文章点击排名:<?php get_mostviewed($limit = 6,30);?> 文章点击排名:<?php get_mostviewed($limit = 25,0);?> */ function get_mostviewed($limit = 5,$limitdays=30,$before = '<li>', $after = '</li>') { //Popular Post From qdkfweb.cn global $wpdb; if($limitdays==0||$limitdays=="") $where = ""; else $where .= " AND post_date > '" . date('Y-m-d', strtotime("-$limitdays days")) . "'"; $most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date < '".current_time('mysql')."' ".$where." AND post_type <> 'page' AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER BY views DESC LIMIT $limit"); if($most_viewed) { foreach ($most_viewed as $post) { global $post; $post_ID = $post->ID; $views = (int)get_post_meta($post_ID, 'views', true); //$post_views = (int)get_post_meta($post_ID, 'views', true); $post_title = htmlspecialchars(stripslashes($post->post_title)); $permalink = get_permalink($post->ID); echo $before ."<a href=\"$permalink\">$post_title </a> <span>$views</span>". $after; } } }
如果你发现问题,可以及时告诉我,或者加入我们的QQ群讨论。