WordPress无需插件实现文章阅读量统计功能
in 各种技术 with 0 comment

WordPress无需插件实现文章阅读量统计功能

in 各种技术 with 0 comment

请输入图片描述
首先我们在functions.php写入代码:

/*
WordPress实现免插件文章阅读量统计
*/
function getPostViews($postID){
    $count_key = 'post_views';
    $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 = 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);
    }
}

之后,我们在single.php中找到这句代码(一般是):

<?php if (have_posts()) : the_post(); update_post_caches($posts); ?>

我们在这句下面加上一句:

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

所以上面的代码就变成了:

<?php if (have_posts()) : the_post(); update_post_caches($posts); ?>
<?php setPostViews(get_the_ID()); ?>

然后我们调用这个代码的时候就用:

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

记得,加到你想要把文章阅读量显示出来的地方。

版权说明:本文转载自“WordPress寻主题”:https://www.wpxzt.com/course/123.html

Responses