Skip to content

Instantly share code, notes, and snippets.

@verticalgrain
Last active September 4, 2017 17:55
Show Gist options
  • Save verticalgrain/9e7faba825aeb679c87c to your computer and use it in GitHub Desktop.
Save verticalgrain/9e7faba825aeb679c87c to your computer and use it in GitHub Desktop.
Example WP Cron job
<?php
// On the scheduled action hook, run a function.
function my_cron_job_function() {
// Put all your codez here
// Sample code fetches a json feed and caches it by saving it as a file
set_time_limit(0);
//File to save the contents to
$fp = fopen ('cachefile-dos.json', 'w+');
//The URL to the json feed you want to cache
$url = "http://ip.jsontest.com/?callback=showMyIP";
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
//give curl the file pointer so that it can write to it
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);//get curl response
//done
curl_close($ch);
// For debugging - send yourself an email when cache rebuilt
//mail("person@domain7.com","Project cache file was rebuilt","The project cache file was rebuilt");
}
add_action( 'my_cron_job', 'my_cron_job_function' );
// Schedule the Cron job with WP Cron
// On an early action hook, check if the hook is scheduled - if not, schedule it.
function setup_cron_schedule() {
if ( ! wp_next_scheduled( 'my_cron_job' ) ) {
wp_schedule_event( time(), 'hourly', 'my_cron_job');
}
}
add_action( 'wp', 'setup_cron_schedule' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment