最好的方法是设置一个自定义表。对于每个视图,您将添加一个新行,其中至少包含uid、帖子id和日期/时间。这种方法的美妙之处在于,您可以在每个视图中存储任意多的数据,例如IP或当前用户(如果他们已登录)。我真的不能给出比这更多的建议,因为我从未尝试使用自定义表,但是有很多插件可以做到这一点。The codex article can be found here.
另一种方法是使用post-meta,类似于您的操作方式。您要做的是存储一个查看时间数组。这样,您就不必存储视图计数,尽管我确信您希望保留旧数据以用于记录。然而,这最终会导致一个非常臃肿的函数试图对您的帖子进行排序。
我已经完成了下面的一些代码,理论上应该可以工作,但我还没有机会测试它。
//Track page view
function track_post_view( $post_id ) {
$views_key = \'post_views_times\';
$views = get_post_meta( $post_id, $views_key, true );
$count = count( $views );
if( $count === 0 ) {
$views = array();
}
//Adds another entry to the views with the current UNIX timestamp
$views[] = time();
return update_post_meta( $post_id, $views_key, $views );
}
//Get all posts
function get_popular_posts( $limit = 3 ) {
$all_posts = new WP_Query( \'post_type\' => \'post\', \'post_status\' => \'publish\' );
//Store these posts
while($all_posts->get_posts()){
$all_posts->the_post();
$post_views = get_post_meta( get_the_ID(), \'post_views_times\' );
$week_ago_time = time() - 7 * 24 * 60 * 60; //This is the timestamp of 1 week ago
for( $i = 0; $i < count( $post_views ); $i++ ){
if( $post_views[$i] < $week_ago_time ){
unset($post_views[$i]); //If the timestamp is less than 1 week ago get remove it from the variable
}
}
$posts_list[] = array( \'views\' => count( $post_views ), \'post_id\' => get_the_ID() );
}
//Get the column to sort the $posts_list by
foreach ($posts_list as $key => $row) {
$views[$key] = $row[\'volume\'];
}
array_multisort( $views, SORT_DESC, $posts_list ); //This sorts descending by views.
//Get the top 3 viewed posts and store that it yet another array
for( $i = 0; $i < $limit; $i++ ){
$most_viewed_ids[] = $posts_list[$i][\'post_id\'];
}
$popular = new WP_Query( \'p\' => $most_viewed_ids ); //Run a query getting our 3 top posts
wp_reset_postdata();
return $popular;
}
我希望这个答案在某种程度上有所帮助