不用插件让WordPress具备显示浏览次数的完美方案

演示效果请看yinke.info网站!虽然笔者之前写了一篇《WordPress文章显示浏览次数的方法》 ,比较详细的介绍了安装WP-PostViews这款插件后修改模板显示浏览次数的方法,但笔者却发现在另外的主题如Twenty Ten中竟然没有找到添加显示次数的地方!于是笔者仔细地查看了一下该主题的模板文件,发现绝大多数功能均是在functions.php模板中通过函数定义,然后在页面、文章等模板中调用函数的方式实现的。于是就动手修改functions.php文件:
将如下代码复制到主题的functions.php文件里的<?php下面的合适位置(我是放在function twentyten_posted_on()之前的!)
if ( ! function_exists( ‘getPostViews’ ) ) :
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 “Just 0 Views”;
 }
 return ‘Just ‘.$count.’ Views’;
}
endif;

if ( ! function_exists( ‘setPostViews’ ) ) :
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);
 }
}
endif;

代码解释:添加的 getPostViews 和 setPostViews 方法分别是获取文章浏览次数和设置文章浏览次数的方法。设置方法是通过文章 ID 将浏览次数信息写入到 post_meta 也就是我们文章的“自定义栏目”内,而获取就是通过文章 ID 从 post_meta 里获取对应信息。刚开始我在  return ‘Just ‘.$count.’ Views’;这一句及其之前的类似语句写成  return ‘阅读了 ‘.$count.’ 次’;结果显示的是乱码,百思不得其解,估计是我是用的cn版wordpress缘故,无法只有改成英文提示了!

然后再修改紧接着的function twentyten_posted_on()函数成如下形式:

function twentyten_posted_on() {
 printf( __( ‘<span>Posted on</span> %2$s <span>by</span> %3$s  %4$s’, ‘twentyten’ ),
  ‘meta-prep meta-prep-author’,
  sprintf( ‘<a href=”%1$s” title=”%2$s” rel=”bookmark”><span>%3$s</span></a>’,
   get_permalink(),
   esc_attr( get_the_time() ),
   get_the_date()
  ),
  sprintf( ‘<span><a href=”%1$s” title=”%2$s”>%3$s</a></span>’,
   get_author_posts_url( get_the_author_meta( ‘ID’ ) ),
   esc_attr( sprintf( __( ‘View all posts by %s’, ‘twentyten’ ), get_the_author() ) ),
   get_the_author()
  ),
  sprintf(‘%1$s’,
   getPostViews(get_the_ID())
  )
 );
}

实际上是增加了一个 %4$s’参数,然后再增加最后一个 sprintf(‘%1$s’,getPostViews(get_the_ID())语句!

(之前我是直接在后台即控制面板中直接修改该functions.php文件,结果只要一更新就提示语法错误,无法,只好将该文件按上述方法修改好后再上传,一切ok,也不知道是哪里出问题了?!)
注意,如果不是 Twenty Ten主题,修改function twentyten_posted_on()函数的这一步应该这样子来理解:即在想要显示文章浏览次数的地方添加如下代码来显示浏览次数:

  <?php echo getPostViews(get_the_ID()); ?>

(代码解释:调用 getPostViews 方法,以获得浏览次数,并且打印显示。可以在index.php、page.php、single.php等文件的合适位置添加!)

同时一定要记得修改当前主题文件里面的single.php文件(文章页面),在<?php get_header(); ?>下添加如下代码:

  <?php setPostViews(get_the_ID()); ?>

(代码解释:这段代码的作用是调用 functions.php 里我们添加的 setPostViews 方法,以实现设置浏览次数。)

That’s Right!一切OK了!按如此方法修改后不仅在首页还是任何页面、分类、文章显示界面下均可完美显示浏览次数了!特此将我辛苦折腾最终完美实现的方法奉献给大家,希望对广大博友有所帮助!

另记:时候笔者又在反思,如果是安装了WP-PostViews这款插件,应该是可以简单的仅仅修改function twentyten_posted_on()函数,然后将上述最后一个 sprintf(‘%1$s’,getPostViews(get_the_ID())语句改成sprintf(‘%1$s’,the_views(); !的样子就ok了(笔者没有测试,爱折腾的就去测试一下吧!)