【问题标题】:Function to track views of post only from past week仅跟踪过去一周的帖子浏览量的功能
【发布时间】:2017-11-29 18:10:05
【问题描述】:

我正在尝试创建一个函数,该函数仅从过去一周的帖子中获取总观看次数。目前该功能正在获取所有时间视图的总数。我基本上希望它在每周开始时重置为 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');

【问题讨论】:

  • 如果我要解决这个问题,我通常会使用两种方法。如果我自己跟踪它,我可以使用 sql 选择上周数据库中的所有视图。第二种更简单的方法是调用谷歌分析 api 并以这种方式获取。
  • @Chris,我该怎么做?

标签: javascript jquery wordpress function


【解决方案1】:

只需检查这是否是一周的第一天和帖子的第一次查看,然后将计数器设置为 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 查询获取每周视图。

【讨论】:

  • 当我尝试在我的页面中添加它时,它变成了空白。您介意在我的代码中发布您的建议吗?
  • 我将我的代码添加到您的函数中(请参阅编辑后的答案)。
  • 现在我的帖子中显示了两个自定义字段 - 一个名为 weekView 并停留在数字 26 和一个名为 wpb_post_views_counts 的字段,它正在计算正确的观看次数。这工作正常吗? wpb_post_views_counts 是不是只统计本周的浏览量,下周重置?
  • 如果有人在下周访问您的帖子,则 weekView 将与 currentWeek 不同,因此您的计数器将重置为 0。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
相关资源
最近更新 更多