Ingo Steinke is a Berlin-based senior web developer focusing on front-end web development to create and improve websites and make the web more accessible, sustainable, and user-friendly.
After pausing my project for a while, there is still no answer.
Meanwhile, I did some more research and experiments. It seems that WordPress cron jobs have the lowest possible rights, just like a visitor who isn't logged in at all, if this StackOverflow answer from 2011 is still correct: WordPress cron is
running as no one, as get_current_user_id() returns 0
I tried setting permissions explicitly, but I suspect we shouldn't be able to elevate the current user's privileges as that would cause a security vulnerability. I'm still not even sure if that's the real problem, but it wouldn't harm to make the scheduled callback inherit the caller's permissions.
I didn't find authoritative statements or code examples in the WordPress Codex, so I proceeded to do some more trial and error and waited for one hour after uploading a new plugin version, as I'm too lazy to define my own interval < 1h. I already proved that my installation can send emails and generate an inbox report and send that by email, at least if it's done outside the scheduled callback below.
functionopenmindculture_cfirm_schedule(){require_once(plugin_dir_path(__FILE__).'generate-report.php');$openmindculture_cfirm_report='';try{$u=newWP_User(3);$u->set_role('administrator');}catch(Exception$ex){$openmindculture_cfirm_report='Failed to set user role for mail report '.$ex->getMessage();}try{// generating the report requires capabilities to access backend data$openmindculture_cfirm_report=openmindculture_generate_report();}catch(Exception$ex){$openmindculture_cfirm_report='Failed to generate report '.$ex->getMessage();}if(!$openmindculture_cfirm_report||empty($openmindculture_cfirm_report)){$openmindculture_cfirm_report='Nothing to report, but the mail interval works.';}require_once(plugin_dir_path(__FILE__).'send-report.php');openmindculture_cfirm_send_report($openmindculture_cfirm_report);}
So no matter what's the problem, I should receive an email soon...
but I didn't!
Do I need to reschedule to make sure that the new callback code is executed?
Maybe! So I rescheduled and waited ... nothing!
I deactivated and uninstalled my plugin. Uploaded my update – which now displays its version number – activated it, checked the settings and report preview, waited again ... no mails! :-(
I added more diagnostics and made the preview page send an additional mail again.
This works:
This message was generated automatically by the Contact Form Inbox Report Mailer WordPress plugin 1.0.3 (current user ID: 1).
Next scheduled email report: 2023-10-09 12:13:40 (server time 2023-10-09 11:48:06)
I can see this message on my plugin page, the scheduled time stamp changes every hour, and I get an email when I open or reload the page. So far, so good.
But no mail gets sent. How can I even be sure that the cron job got called at all?
And why there so little detailed documentation about this topic?
Ingo Steinke is a Berlin-based senior web developer focusing on front-end web development to create and improve websites and make the web more accessible, sustainable, and user-friendly.
I installed WP Crontrol to show more information about scheduled jobs and intervals. There are much more than I expected, and there is the one scheduled by my report mailer plugin.
And it's got an unexpected problem: it's got no action!
I must have made a mistake in my callback definition.
I see that my implicit assumption about the third parameter was wrong.
$hook string Required Action hook to execute when the event is run
makes it quite clear that wp_schedule_event doesn't expect a function but an action hook. That's basically an additional wrapper around the existing function. I could have copied the first user provided code example in the comments.
if(!wp_next_scheduled('my_hourly_event',$args)){wp_schedule_event(time(),'hourly','my_hourly_event',$args);}add_action('my_hourly_event','do_this_hourly',10,2);functiondo_this_hourly($args_1,$args_2){// do something every hour}
We can even pass arguments (and if we don't, we need to change the 2 to 0 in add_action).
But we still can't pass user sessions and their permissions.
Ingo Steinke is a Berlin-based senior web developer focusing on front-end web development to create and improve websites and make the web more accessible, sustainable, and user-friendly.
I discovered that we can fire a single scheduled event immediately from the WP Crontrol list view. Although the callback action evaluates to the existing function name, nothing happens. No empty mail, no echo output. So there is still something wrong with my schedule or callback.
Meanwhile, I had another idea.
If I had access to the SQL database, I could write a simple query like
SELECT * FROM wp_posts WHERE post_type = 'flamingo_inbound' AND post_date > '2023-10-09 08:07'
That would also assume that I know the current table prefix and the connection details.
But $wpdb knows.
global$wpdb;$results=$wpdb->get_results("SELECT * FROM {$wpdb->prefix}posts WHERE post_type = 'flamingo_inbound'",OBJECT);
Of course, it wouldn't let me retrieve arbitrary data using a custom SQL statement without adding a capability constraint.
Ingo Steinke is a Berlin-based senior web developer focusing on front-end web development to create and improve websites and make the web more accessible, sustainable, and user-friendly.
[ ] WordPress custom user role for cron schedule callback
So we still can't pass user sessions and their permissions when scheduling our cron job.
And I still don't get how WordPress offers no best practice how to handle this requirement safely.
Allowing everyone access to the inbox items is no solution. Even if there are no public pages exposing this data, someone might still try and access it via an API call.
Running all cron schedule callbacks with administrator rights is no good solution either. We shouldn't even run this very specific job as an administrator.
Using a real cron job with file access on a UNIX system, I would create a unique new user and add it to a group of users. Then I would let this user group own the required file and set group permissions accordingly.
There are equivalent concepts in WordPress. User roles correspond to user groups, permissions correspond to their capabilities. As an administrator, which is roughly equivalent to an Administrator on Windows, not to a UNIX root, we should have sufficient capabilities to set permissions accordingly. But if the schedule callback runs as nobody, changing its role to anybody would be a privilege escalation. Do we have any chance to run a callback as somebody under any circumstances at all?
Ingo Steinke is a Berlin-based senior web developer focusing on front-end web development to create and improve websites and make the web more accessible, sustainable, and user-friendly.
Several days later, suddenly, some mails in my inbox!
nothing to report, but the mail interval works
Maybe "hourly" means "daily" or "weekly" on a WordPress website with few visitors? Or maybe frontend caching prevents triggering the wp cron job schedule?
Some people seemed to have caching vs. wp cron issues.
But in my case, the "next scheduled" time changed and still it seemed that my cron callback was not executed.
Ingo Steinke is a Berlin-based senior web developer focusing on front-end web development to create and improve websites and make the web more accessible, sustainable, and user-friendly.
After talking to myself in support issues, like I often do, logging erratic plugin behavior, and nobody seems to be able to help, I will test alternative solutions:
switch caching plugins to verify if it is W3TC related or if the same problems occurs with WP Rocket or other alternatives,
use an alternative to WP_Cron which seems like an unrealiable hack anyway.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
After pausing my project for a while, there is still no answer.
Meanwhile, I did some more research and experiments. It seems that WordPress cron jobs have the lowest possible rights, just like a visitor who isn't logged in at all, if this StackOverflow answer from 2011 is still correct: WordPress cron is
I tried setting permissions explicitly, but I suspect we shouldn't be able to elevate the current user's privileges as that would cause a security vulnerability. I'm still not even sure if that's the real problem, but it wouldn't harm to make the scheduled callback inherit the caller's permissions.
I didn't find authoritative statements or code examples in the WordPress Codex, so I proceeded to do some more trial and error and waited for one hour after uploading a new plugin version, as I'm too lazy to define my own interval < 1h. I already proved that my installation can send emails and generate an inbox report and send that by email, at least if it's done outside the scheduled callback below.
So no matter what's the problem, I should receive an email soon...
but I didn't!
Do I need to reschedule to make sure that the new callback code is executed?
Maybe! So I rescheduled and waited ... nothing!
I deactivated and uninstalled my plugin. Uploaded my update – which now displays its version number – activated it, checked the settings and report preview, waited again ... no mails!
:-(I added more diagnostics and made the preview page send an additional mail again.
This works:
I can see this message on my plugin page, the scheduled time stamp changes every hour, and I get an email when I open or reload the page. So far, so good.
But no mail gets sent. How can I even be sure that the cron job got called at all?
And why there so little detailed documentation about this topic?
I installed WP Crontrol to show more information about scheduled jobs and intervals. There are much more than I expected, and there is the one scheduled by my report mailer plugin.
And it's got an unexpected problem: it's got no action!
I must have made a mistake in my callback definition.
Revisiting the documentation
I see that my implicit assumption about the third parameter was wrong.
makes it quite clear that
wp_schedule_eventdoesn't expect a function but an action hook. That's basically an additional wrapper around the existing function. I could have copied the first user provided code example in the comments.We can even pass arguments (and if we don't, we need to change the
2to0inadd_action).But we still can't pass user sessions and their permissions.
I discovered that we can fire a single scheduled event immediately from the WP Crontrol list view. Although the callback action evaluates to the existing function name, nothing happens. No empty mail, no echo output. So there is still something wrong with my schedule or callback.
Meanwhile, I had another idea.
If I had access to the SQL database, I could write a simple query like
SELECT * FROM wp_posts WHERE post_type = 'flamingo_inbound'AND post_date > '2023-10-09 08:07'That would also assume that I know the current table prefix and the connection details.
But
$wpdbknows.Of course, it wouldn't let me retrieve arbitrary data using a custom SQL statement without adding a capability constraint.
Or would it?
Proceeding to talk to myself, hoping for a solution to set WP schedule event role and permissions (capabilities):
So we still can't pass user sessions and their permissions when scheduling our cron job.
And I still don't get how WordPress offers no best practice how to handle this requirement safely.
Allowing everyone access to the inbox items is no solution. Even if there are no public pages exposing this data, someone might still try and access it via an API call.
Running all cron schedule callbacks with administrator rights is no good solution either. We shouldn't even run this very specific job as an administrator.
Using a real cron job with file access on a UNIX system, I would create a unique new user and add it to a group of users. Then I would let this user group own the required file and set group permissions accordingly.
There are equivalent concepts in WordPress. User roles correspond to user groups, permissions correspond to their capabilities. As an administrator, which is roughly equivalent to an Administrator on Windows, not to a UNIX root, we should have sufficient capabilities to set permissions accordingly. But if the schedule callback runs as nobody, changing its role to anybody would be a privilege escalation. Do we have any chance to run a callback as somebody under any circumstances at all?
Several days later, suddenly, some mails in my inbox!
Maybe "hourly" means "daily" or "weekly" on a WordPress website with few visitors? Or maybe frontend caching prevents triggering the wp cron job schedule?
Some people seemed to have caching vs. wp cron issues.
But in my case, the "next scheduled" time changed and still it seemed that my cron callback was not executed.
After talking to myself in support issues, like I often do, logging erratic plugin behavior, and nobody seems to be able to help, I will test alternative solutions: