我目前正在使用此代码显示按查看次数排序的最受欢迎的帖子,该帖子到目前为止运作良好:
/**
* 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');
我想按小时将视图计数重置为0,但我不太清楚如何去做。我已经使用下面的代码,但到目前为止还没有任何运气。这是正确的方向吗?
/**
* 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' );
任何帮助都会受到大力赞赏!
答案 0 :(得分:0)
我认为问题可能与您使用get_posts()
...
您传递了meta_key
,但没有给它一个值来检查meta_value
。
尝试从你的args中删除meta_key
行。
meta_key
应该像:
$args = array(
'numberposts' => -1,
'meta_key' => 'color',
'meta_value' => 'red',
'post_type' => 'event',
'suppress_filters' => true
);
这会获取color
postmeta字段的所有帖子,其值为red
希望这会有所帮助。我认为你的代码非常接近。