execute function in wordpress plugin using crontab

So, I want to run a function on my plugin from crontab. For the example, I want to run it every day at 1:10am

function my_cronjob_action () {
    //this function is in my plugin
    // code to execute on cron run
    syslog(LOG_DEBUG, 'executed by unix cron');
} add_action('my_cronjob_action', 'my_cronjob_action');

I’ve disabled wp-cron by adding define( 'DISABLE_WP_CRON', true ); into wp-config.php
what’s the next step so the function can be executed from crontab?

Thank you before.

1 Answer
1

I found a great solution here: Trigger a custom wordpress plugin with a linux cron

My path was /usr/bin/wp so check your server.

You can just add your function to a file, and using the wp bin script you don’t need to add anything to your php file to use WordPress functions.

I was able to run this from SSH / putty but I cannot get it to work as a cron job currently. I’l update if I figure out how.

The solution I came up with here goes as follows:

  1. Installed WP-CLI and made use of the eval-file command.
  2. Converted my wordpress plugin to a standalone script.
  3. In the standalone script, I initiated wordpress so i didn’t have to modify most of it. I just removed my the activation hooks and other wordpress plugin specific code.
  4. My final cron line looked like this:
    /usr/local/bin/wp –path=”/var/www/vhosts/path/to/site/” eval-file /var/www/vhosts/path/to/site/and/file/location/standalone-cron-send-email.php
  5. For security purposes, I’ve added this to the top of the script so outside intruders can not run the script. Only WP-CLI can run the script otherwise the meant to be run from command line message is returned to the browser.

if( php_sapi_name() !== ‘cli’ ) { die(“Meant to be run from command line”); }

Leave a Comment