A-A+

分享两个代码实现WordPress文章阅读次数

2013年03月12日 WordPress 暂无评论 阅读 1,859 views 次

代码一:

一、首先将下面代码加到主题functions模版文件中:

  1. function getPostViews($postID){
  2.     $count_key = 'post_views_count';
  3.     $count = get_post_meta($postID, $count_key, true);
  4.     if($count==''){
  5.         delete_post_meta($postID, $count_key);
  6.         add_post_meta($postID, $count_key, '0');
  7.         return "0 View";
  8.     }
  9.     return $count.' Views';
  10. }
  11. function setPostViews($postID) {
  12.     $count_key = 'post_views_count';
  13.     $count = get_post_meta($postID, $count_key, true);
  14.     if($count==''){
  15.         $count = 0;
  16.         delete_post_meta($postID, $count_key);
  17.         add_post_meta($postID, $count_key, '0');
  18.     }else{
  19.         $count++;
  20.         update_post_meta($postID, $count_key, $count);
  21.     }
  22. }

二、接下来将下面代码加到主题single模版主循环的中:

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

也就是类似这句的下面

  1. <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

三、最后,将调用显示阅读次数代码加到single模版适当的位置:

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

如果想在其它位置显示阅读次数,可以将下面代码也加到functions模版中:

  1. remove_action('wp_head','adjacent_posts_rel_link_wp_head',10,0);

 

 

代码二:

一、同样将下面代码加到主题functions模版文件中:

  1. //postviews
  2. function get_post_views ($post_id) {
  3.     $count_key = 'views';
  4.     $count = get_post_meta($post_id, $count_key, true);
  5.     if ($count == '') {
  6.         delete_post_meta($post_id, $count_key);
  7.         add_post_meta($post_id, $count_key, '0');
  8.         $count = '0';
  9.     }
  10.     echo number_format_i18n($count);
  11. }
  12. function set_post_views () {
  13.     global $post;
  14.     $post_id = $post -> ID;
  15.     $count_key = 'views';
  16.     $count = get_post_meta($post_id, $count_key, true);
  17.     if (is_single() || is_page()) {
  18.         if ($count == '') {
  19.             delete_post_meta($post_id, $count_key);
  20.             add_post_meta($post_id, $count_key, '0');
  21.         } else {
  22.             update_post_meta($post_id, $count_key, $count + 1);
  23.         }
  24.     }
  25. }
  26. add_action('get_header', 'set_post_views');

二、将调用显示阅读次数代码加到single模版适当的位置:

  1. <?php get_post_views($post -> ID); ?> views

调用显示阅读次数代码也可以加到其它模版文件的适当位置。

标签:

给我留言

Copyright © 严佳冬 保留所有权利.   Theme  Ality 百度地图 苏ICP备19045515号-2

用户登录

分享到: