刷新页面时限制POST VIE计数的增量

时间:2019-09-21 作者:Gissipi_453

我使用帖子视图计数器保存帖子视图-

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;
}
问题是,每次手动刷新帖子页面时,视图都会增加1。我需要检查一下这个。怎样

1 个回复
最合适的回答,由SO网友:Rafiq 整理而成

您可以使用Transients API

参见示例

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);
        }
    }
 }
}

相关推荐

migrate only recent posts

有没有一种简单的方法可以将最后五篇左右的帖子转移到开发人员站点上?这是live站点的克隆,但在我们克隆live站点后,人们一直在更新它。