首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

不要插件WordPress显示文章浏览次数

2012-09-10 
不用插件WordPress显示文章浏览次数新安装wordpress发现没有显示文章浏览次数的功能…+.+把下面的代码复制

不用插件WordPress显示文章浏览次数

新安装wordpress发现没有显示文章浏览次数的功能…+.+

把下面的代码复制到主题的functions.php文件里,然后按照步骤1和步骤2的说明进行操作,就可以显示每篇文章的被浏览次数。

1234567891011121314151617181920212223
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);    }}

?

代码解释:添加的 getPostViews 和 setPostViews 方法分别是获取文章浏览次数和设置文章浏览次数的方法。设置方法是通过文章 ID 将浏览次数信息写入到 post_meta 也就是我们文章的“自定义栏目”内,而获取就是通过文章 ID 从 post_meta 里获取对应信息。
步骤一:
然后修改 single.php 文件,在主循环内添加如下代码:

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

代码解释:这段代码的作用是调用 functions.php 里我们添加的 setPostViews 方法,以实现设置浏览次数。
最后,我们在想要显示文章浏览次数的地方添加如下代码即可。
步骤二:

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

代码解释:作用同上,只不过是调用 getPostViews 方法,以获得浏览次数,并且打印显示。
需要注意的是这个方法在安装了缓存插件的情况下不适用。

热点排行