您现在的位置是:首页 > 教程 > WordPress教程WordPress教程

wordpress文章阅读次数显示的实现方法

白晴2025-03-27 13:50:43WordPress教程已有4人查阅

导读相信不少博客都是用wordpress搭建的,那么我们在不使用插件的情况下如何简单地实现文章阅读次数的统计呢?下面有两个方法可供参考:方法一:1、首先打开我们的后台控制面板,点击外

相信不少博客都是用wordpress搭建的,那么我们在不使用插件的情况下如何简单地实现文章阅读次数的统计呢?下面有两个方法可供参考:
方法一:
1、首先打开我们的后台控制面板,点击外观--编辑
2、在右栏找到函数模板function.php
在文件的最末尾添加如下代码
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";
}
return '阅读次数 '.$count;
}
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);
}
}
添加之后记得更新文件
3、然后我们打开文章页面single.php,找到与下面类似的地方
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
在它的下面添加如下代码
<?php setPostViews(get_the_ID()); ?>
之后将我们需要展示阅读次数的地方添加如下代码
<?php echo getPostViews(get_the_ID()); ?>
方法二:
1、和方法一一样,找到function.php添加如下代码:
function get_post_views ($post_id) {
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
$count = '0';
}
echo number_format_i18n($count);
}
function set_post_views () {
global $post;
$post_id = $post -> ID;
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if (is_single() || is_page()) {
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
} else {
update_post_meta($post_id, $count_key, $count + 1);
}
}
}
add_action('get_header', 'set_post_views');
然后在文章页面single.php的需要显示的位置添加如下代码
阅读次数
<?php get_post_views($post -> ID); ?>
效果:
注意:如果部分博主使用的主题是特殊的主题,那么文章页面应该是loop-single.php,把上面方法里面的single.php替换成loop-single.php即可

本文标签:

很赞哦! (0)

暂无内容
暂无内容
暂无内容
暂无内容
留言与评论 (共有 0 条评论)
昵称:
匿名发表 登录账号
         
验证码: