wp_schedule_event() 就是你要找的。使用此函数,您可以创建一个cron jon,Wordpress将在您配置的特定时间间隔内执行该操作。此函数应仅在插件激活时调用,并且应在插件停用时清除计划事件。例如:
//Create the weekly and monthly interval
add_filter(\'cron_schedules\', \'cyb_cron_schedules\');
function cyb_cron_schedules( $schedules ) {
$schedules[\'weekly\'] = array(
\'interval\' => 604800, //that\'s how many seconds in a week, for the unix timestamp
\'display\' => __(\'weekly\')
);
$schedules[\'monthly\'] = array(
\'interval\' => 2592000, //that\'s how many seconds in a month (30 days), for the unix timestamp
\'display\' => __(\'monthly\')
);
return $schedules;
}
register_activation_hook( __FILE__, \'cyb_activation\' );
function cyb_activation() {
//Unix timestamp for first run of the event. time() for now
$firstrun = time();
wp_schedule_event( $firstrun, \'weekly\', \'cyb_clear_weekly_post_views\' );
wp_schedule_event( $firstrun, \'monthly\', \'cyb_clear_monthly_post_views\' );
}
register_deactivation_hook( __FILE__, \'cyb_deactivation\' );
function cyb_activation() {
wp_clear_scheduled_hook( \'cyb_clear_weekly_post_views\' );
wp_clear_scheduled_hook( \'cyb_clear_monthly_post_views\' );
}
function cyb_clear_weekly_post_views() {
//Set post_views_count_weekly to 0. Doing this for all post may need a lot of resources
$posts = get_posts(array(\'numberposts\' => -1) );
foreach($posts as $post) {
update_post_meta($post->ID, \'post_views_count_weekly\', 0);
}
}
function cyb_clear_monthly_post_views() {
//Set post_views_count_monthly to 0. Doing this for all post may need a lot of resources
$posts = get_posts(array(\'numberposts\' => -1) );
foreach($posts as $post) {
update_post_meta($post->ID, \'post_views_count_monthly\', 0);
}
}
注意:如果需要以精确的间隔运行计划的事件,则应在服务器中创建cron jon,而不是使用
wp_schedule_event()
. 中的更多信息
wp_schedule_event().