WordPress的缓存停止视图计数器

时间:2018-08-08 01:42:02

标签: php wordpress caching counter-cache hitcounter

目前,我在类似于YouTube的视频托管网站上使用Wordpress主题。当用户在我的网站上观看视频时,观看次数会增加1。

我最近启用了WP Total Cache插件,现在每次用户单击视频时视图都不会增加,因为计数器基于cookie /用户会话。

下面的代码是用于视图计数器的代码。我不太了解,但是我想弄清楚每次用户单击视频时可以进行哪些更改以使计数增加:

if( !function_exists('mars_get_count_viewed') ){
function mars_get_count_viewed() {
    global $post;
    if( isset( $post->ID ) && function_exists( 'stats_get_csv' ) ){

        if( get_transient( 'postviews_' . $post->ID ) !== false ){
            return get_transient( 'postviews_' . $post->ID );
        }

        $random = mt_rand( 9999, 999999999 ); // hack to break cache bug

        $args = array(
            'days' => $random,
            'post_id' => $post->ID,
        );

        $stats = stats_get_csv( 'postviews', $args );
        $views = ( isset( $stats['0']['views'] ) &&  $stats['0']['views'] > 0 ) ? $stats['0']['views'] : 0;
        $views = (int)$views;
        if( $views > 0 ){
            // save transient.
            // 1/2 day.
            set_transient( 'postviews_' . $post->ID , $views, 60*60*1*6 );
        }
        return $views;
    }
    return get_post_meta( $post->ID,'count_viewed',true );
}
}


if( !function_exists('mars_update_post_view') ){
function mars_update_post_view() {

    global $post;
    if(!isset($_SESSION)){ session_start();} 

    if( is_single() ){

        if( isset( $_SESSION['count_viewed'] ) ){
            if( in_array( $post->ID, $_SESSION['count_viewed'] ) ){
                return;
            }
        }
        $current_viewed = mars_get_count_viewed();
        update_post_meta($post->ID, 'count_viewed', $current_viewed + 1);
        $_SESSION['count_viewed'][] = $post->ID;

    }
}
add_action('wp', 'mars_update_post_view');
}

如您所见, mars_get_count_viewed 函数仅获取视频的当前观看次数。因此,我需要更改 mars_update_post_view 中的代码。

也许我可以删除会话并仅更新每个视图?

0 个答案:

没有答案