wp_schedule_event() is what you are looking for. With this function you can create a cron jon that WordPress will axecute on the specific interval you configure. This function should be called only on plugin activation and the scheduled event should be cleared on plugin deactivation. For example:
//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);
}
}
Note: if you need to run the scheduled event on a exact interval you should created a cron jon in your sever instead of using wp_schedule_event()
. More info in wp_schedule_event().