[英]Resetting the post count every hour
I'm currently using this code to display the most popular post sorted by view count which has worked well so far: 我目前正在使用此代码来显示按观看次数排序的最受欢迎的帖子,到目前为止效果很好:
/**
* Count visits to post.
*/
function wpb_set_post_views($postID) {
$count_key = 'wpb_post_views_count';
$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);
/**
* Single post count code
*/
function wpb_track_post_views ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
wpb_set_post_views($post_id);
}
add_action( 'wp_head', 'wpb_track_post_views');
I would like to reset the view count to 0 on an hourly basis but I'm not too sure how to go about it. 我想每小时将视图计数重置为0,但是我不太确定如何处理。 I've had a go using the code below but haven't had any luck so far. 我可以使用下面的代码,但到目前为止还没有运气。 Is this the right direction to be going in? 这是正确的方向吗?
/**
* Reset the post views on hourly basis.
*/
if ( ! wp_next_scheduled( 'daily_cron_action' ) ) {
wp_schedule_event( time(), 'hourly', 'daily_cron_action' );
}
function reset_postview_counters() {
$count_key = 'wpb_post_views_count';
$args = array(
'numberposts' => -1,
'meta_key' => $count_key,
'post_type' => 'event',
'suppress_filters' => true
);
$postslist = get_posts( $args );
foreach ( $postslist as $singlepost ) {
delete_post_meta( $singlepost->ID, $count_key );
}
}
add_action( 'daily_cron_action', 'reset_postview_counters' );
Any help would be massively appreciated! 任何帮助将不胜感激!
I think the issue might be something to do with the way you are using get_posts()
... 我认为问题可能与您使用get_posts()
...
You're passing in a meta_key
, but not giving it a value to check against with meta_value
. 您正在传递meta_key
,但没有给它提供一个值来与meta_value
。
Try just removing the meta_key
line from your args. 尝试仅从参数中删除meta_key
行。
The meta_key
should be used like: meta_key
应类似于:
$args = array(
'numberposts' => -1,
'meta_key' => 'color',
'meta_value' => 'red',
'post_type' => 'event',
'suppress_filters' => true
);
That would grab all the posts with the color
postmeta field where the value is red
这将使用color
postmeta的字段获取所有帖子,其中值是red
Hope this helps. 希望这可以帮助。 Your code is really close I think. 我认为您的代码非常接近。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.