zoukankan      html  css  js  c++  java
  • wordpress实现文章阅读次数

    相信不少博客都是用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即可
     

  • 相关阅读:
    2-6 R语言基础 缺失值
    2-5 R语言基础 factor
    2-4 R语言基础 列表
    2-3 R语言基础 矩阵和数组
    2-2 R语言基础 向量
    【转】Python操作MongoDB数据库
    Python程序的执行原理
    数据分析的职业规划
    自定义菜单 开发 服务器繁忙
    微信自定义菜单
  • 原文地址:https://www.cnblogs.com/xiaogou/p/11660491.html
Copyright © 2011-2022 走看看