我正在尝试创建一个仅能获取过去一周内帖子总数的函数。当前,该函数正在获取所有时间视图的总数。我基本上希望每个星期初将其重置为0。这可能吗?我该怎么办?

// Popular Posts Week
function wpb_set_post_viewss($postID) {
    $count_key = 'wpb_post_views_counts';
    $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);
    }
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
function wpb_track_post_viewss ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;
    }
    wpb_set_post_viewss($post_id);
}
add_action( 'wp_head', 'wpb_track_post_viewss');

最佳答案

只需检查这是星期几还是该帖子的第一个视图,然后将计数器设置为0即可。

function wpb_set_post_viewss($postID) {

    $currentWeekNumber = date('W');

    $count_key = 'wpb_post_views_counts';
    $count = get_post_meta($postID, $count_key, true);
    $weekView = get_post_meta($postID, 'weekView', true);

    if($weekView != $currentWeekNumber){
        update_post_meta($postID, 'weekView', $currentWeekNumber);
        update_post_meta($postID, $count_key, '0');
    } else {
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}


您还可以将所有视图存储在数据库中,并通过一个SQL查询获得每周视图。

10-07 23:18