Last active
September 4, 2017 17:55
-
-
Save verticalgrain/9e7faba825aeb679c87c to your computer and use it in GitHub Desktop.
Example WP Cron job
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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