WordPress查询浏览量需要用什么代码 WordPress网站建站教程

凤凰 2021-1-19 79 1/19

WordPress查询浏览量需要用什么代码 WordPress网站建站教程

用wordpress 搭建的博客或者企业站都有着同样的需求,就是在内容页面需要统计这个页面的浏览次数,以方便站长查看某个页面的仿问题,一般对代码不熟悉的朋友都会用到浏览次数统计插件(WP-PostViews),但是众所周知,一个站点如果插件安装的多了会对SEO优化 非常不利,那么下面给大家分享一个利用代码来实现这种浏览次数的统计功能。

1、在functions.php函数文件的未尾另起一行,添加如下代码。

<?php
/* Postviews start */
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);
    }
}
/* Postviews start end*/
?>

2、在您需要显示统计浏览次数的页面,例如在single.php内容页面中的<?php endwhile; ?>和<?php endif; wp_reset_query(); ?>循环语句的中间添加以下代码:

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

添加后的显示,如:

 <?php endwhile; ?>
     <?php setPostViews(get_the_ID());?>
<?php endif; wp_reset_query(); ?>

3、最后在您需要显示统计的地方添加如下代码:

<?php echo getPostViews(get_the_ID()); ?> 次浏览

更多wordpress相关技术文章,请访问wordpress教程栏目进行学习!

以上就是wordpress查询浏览量需要用什么代码的详细内容,更多请关注本站其它相关文章!

- THE END -

凤凰

1月19日09:20

最后修改:2021年1月19日
0

非特殊说明,本博所有文章均为博主原创。