13071077710
您的当前位置: 首页 > wordpress > wordpress给文章添加浏览次数统计功能

wordpress给文章添加浏览次数统计功能

时间: 2016-8-25

1.在主题的 functions.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');

2.在需要显示该统计次数的地方使用下面的代码调用:

<?php get_post_views($post -> ID); ?>

Copyright © 2013-2019 子歇    版权所有   网站地图