有人能给我指出正确的方向吗?
我正在尝试设置一个插件,该插件在激活时设置cron作业,以在用户的user\\u注册日期3个月后更改用户的user\\u角色。当插件被停用时,cron作业也应该被删除。
目前,以下代码不起作用。cron作业将运行,但用户角色不会更新。
The plugin code so far is:
<?php
/*
Plugin Name: Cron Job
*/
add_filter( \'cron_schedules\', \'example_add_cron_interval\' );
function example_add_cron_interval( $schedules ) {
$schedules[\'five_seconds\'] = array(
\'interval\' => 5,
\'display\' => esc_html__( \'Every Five Seconds\' ),
);
return $schedules;
}
function cron_hook(){
$users = get_users(
array(
\'fields\' => array( \'ID\', \'user_registered\' ),
\'role\' => \'coaching\',
)
);
foreach ( $users as $user ) {
$time = $user->user_registered;
if(strtotime($time) < strtotime(\'-3 months\')) {
$u = new WP_User( $user->ID );
// Remove role
print_r($u);
$u->remove_role( \'coaching\' );
// Add role
$u->add_role( \'platinum\' );
}
}
}
//echo \'<pre>\'; print_r( _get_cron_array() ); echo \'</pre>\';
public static function activate() {
wp_schedule_event( time(), \'five_seconds\', \'cron_job\' );
}
public static function deactivate() {
wp_clear_scheduled_hook(\'cron_job\');
}
我正在运行wp cron。php到cPanel(当前测试设置为5\\u秒)。
SO网友:gromey
设法找到了解决方案。
我完成的代码是:
register_activation_hook ( __FILE__, \'cron_job\' );
function cron_job()
{
wp_schedule_event( time(), \'hourly\', \'hourly_job\' );
}
add_action( \'hourly_job\', \'cron_job_task\' );
function cron_job_task ()
{
$users = get_users(
array(
\'fields\' => array( \'ID\', \'user_registered\' ),
\'role\' => \'coaching\',
)
);
foreach ( $users as $user ) {
$time = $user->user_registered;
if(strtotime($time) < strtotime(\'-3 months\')) {
$u = new WP_User( $user->ID );
$u->remove_role( \'coaching\' );
$u->add_role( \'platinum\' );
}
}
}
?>
每小时设置一个cPanel cron作业。