在X小时、分钟或秒后重置/删除帖子视图元/自定义域

时间:2016-07-12 作者:Pete

有很多代码片段和插件可以计算帖子的浏览量,但我正试图找到一种方法,在X小时(或分或秒或其他时间)后将浏览量重置为零。

我想我需要合并this <?php delete_post_meta($post_id, $meta_key, $meta_value); ?>

这里是the snippet 我正在使用。。。

function getPostViews($postID){
    $count_key = \'post_views_count\';
    $count = get_post_meta($postID, $count_key, true);
    if($count==\'\'){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, \'0\');
        return "0 View";
    }
    return $count.\' Views\';
}
function setPostViews($postID) {
    $count_key = \'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);
    }
}
// Remove issues with prefetching adding extra views
remove_action( \'wp_head\', \'adjacent_posts_rel_link_wp_head\', 10, 0);
这个cron可以工作吗?

<?php 
if ( ! wp_next_scheduled( \'my_task_hook\' ) ) {
  wp_schedule_event( time(), \'daily\', \'my_task_hook\' );
}

add_action( \'my_task_hook\', \'my_task_function\' );

function my_task_function() {
  delete_post_meta($post_id, \'post_views_count\', true);
}
?>

1 个回复
SO网友:Ehsaan

安排事件的代码不正确,以下是正确的代码:

function hits_set_zero_schedule() {
  if ( ! wp_next_scheduled( \'hits_set_to_zero\') )
    wp_schedule_event( time(), \'daily\', \'hits_set_zero\' );
}
add_action( \'wp\', \'hits_set_zero_schedule\' );

function hits_set_zero_func() {
  delete_post_meta( $post_id, \'post_views_count\', true );
}
add_action( \'hits_set_zero\', \'hits_set_zero_func\' );
此外,您可以定义间隔,而不是daily 通过向代码中添加一个小片段:

add_filter( \'cron_schedules\', \'my_custom_schedule\' );
function my_custom_schedule( $schedules ) {
    $schedules[ \'five_minutes\' ] = array(
        \'interval\'          =>  5 * 60,
        \'display\'           =>  \'Once five minutes\'
    );

    return $schedules;
}
您可以更改interval 中的元素$schedules 元素,以秒为单位。