最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - restrict incrementation of post vies count when refreshing the page

programmeradmin1浏览0评论

I use a post views counter to save post views -

function calculatePostViews($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, '1');
        return;
    }
    $count++;
    update_post_meta($postID, $count_key, $count);
    return;
}

The issue is, everytime the post page is refreshed manually, the view increments by 1. I need to check this. How ?

I use a post views counter to save post views -

function calculatePostViews($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, '1');
        return;
    }
    $count++;
    update_post_meta($postID, $count_key, $count);
    return;
}

The issue is, everytime the post page is refreshed manually, the view increments by 1. I need to check this. How ?

Share Improve this question asked Sep 21, 2019 at 5:30 Gissipi_453Gissipi_453 1053 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

You can use Transients API

See the example

function calculatePostViews($postID){

      $user_ip = $_SERVER['REMOTE_ADDR']; //retrieve the current IP address of the visitor
    $key = $user_ip . 'x' . $postID; //combine post ID & IP to form unique key
    $value = array($user_ip, $postID); // store post ID & IP as separate values (see note)
    $visited = get_transient($key); //get transient and store in variable

    //check if user not administrator, if so execute code block within
    if( !current_user_can('administrator') ) {
    //check to see if the Post ID/IP ($key) address is currently stored as a transient
    if ( false === ( $visited ) ) {
        //store the unique key, Post ID & IP address for 12 hours if it does not exist
        set_transient( $key, $value, 60*60*12 );

        // now run post views function
        $count_key = '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);
        }
    }
 }
}
发布评论

评论列表(0)

  1. 暂无评论