2014年8月7日
wordpress用代码实现显示文章浏览数
在文章的相关信息中显示出文章浏览数可以令人鼓舞,也可令人反省。我尝试时的参考链接:http://www.wordpress.la/track-wordpress-post-views-without-plugins.html。
1.在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 27 28 29 |
function getPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0 View"; } return $count.' Views'; } function setPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); } else { $count++; update_post_meta($postID, $count_key, $count); } } |
2.将以下代码插入single.php文件主循环内。
1 2 3 |
<?php setPostViews(get_the_ID()); ?> |
所谓的主循环内,指的是while与endwhile之间的部分。
1 2 3 4 5 |
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> . . . <?php endwhile; /* end loop */ ?> |
3.将下面代码插入想让浏览数出现的位置。
1 2 3 |
<?php echo getPostViews(get_the_ID()); ?> |
例如我想让浏览数出现在小站的文章页,我就将上述代码加在了single.php的相应处。本来还想将该代码加到首页的,不过还没有找到合适的图片,加上去似乎有点不伦不类,暂时作罢。
1 2 3 4 5 6 7 8 9 |
<header> <h1 class="title single-title"><?php the_title(); ?></h1> <span class="theauthor single-postmeta"><?php _e('Posted in ','mythemeshop'); the_category(' • '); ?><?php _e(' By ','mythemeshop'); the_author_posts_link(); ?><?php _e(' On ','mythemeshop'); the_time('Y年n月j日'); ?> <?php _e(',','mythemeshop');?><!--新添加部分,为了将浏览数与前面内容分开--> <?php echo getPostViews(get_the_ID()); ?><!--新添加部分,显示浏览数--> </span> </header><!--.headline_area--> |