I have created a plugin that adds products programatically to WooCommerce. The plugin is working great, but now I need to make a cron job that runs every 5 minutes to update the inventory.
I have the script all written but I need to include calls to get_option() in this php file to get certain plugin values that the user has entered. However, I can’t just include get_option()
in this file because it is outside of the WordPress core. So my thought would be to put in require( 'path/to/wp-load.php' );
which I know you aren’t really supposed to do. Anyway it fixes the issue if you hit the page via a web browser request. However the cron job fails the moment that this file is included because somewhere with wp-load.php it is sending HTTP_Header requests.
Any thoughts or solutions? I tried to add define('WP_USE_THEMES', false);
right above the requiring of wp-load.php but it is still causing the cron job to fail.
Long winded I know, but how do you include get_option()
requests inside of a external PHP script that will be accessed via a PHP cron job.
Thanks much.
The quick and easy way
The problem is probably that you try to include wp-load.php from a wrong path. In a CLI environment, the path would not be the same as when you do an HTTP request to the file. So with this you should fixed your issue:
The proper but longer way
Based on cale_b comments and this article he linked, there is a much proper way to go by doing a WordPress Cron job.
First in your plugin add a function that will contain the code needed to be executed, let’s call it
my_cron_job()
. You can eventually just include the script you already wrote in this function. Then add the following to schedule the execution of this every 5min:Then set up your cron to execute wp-cron.php every 5 minutes:
Update
First when choosing the option of executing wp-cron.php with a server cron you should disable the default WP Cron behaviour (execution of cron through web visits):
Secondly, as for your question about WP Cron reliability I see a potential flaw indeed. I’m not 100% sure of that, but I think it is possible that
wp_schedule_event
get desynchronized with the server cron, as the job get executed only if the interval is past. As it will be re-scheduled depending of the execution time of the script which is slightly different with the server cron time.For example:
That’s theory of course, maybe this is not accurate. I suggest doing some test and see how it behave. If it indeed behave like I think it did, I suggest as easy workaround to change the
wp_schedule_event
to a lower interval – 4min for example.So we’ll have the following:
With the default WP Cron behaviour disabled it should work flawlessly.