Today I’ve tried to write a WordPress Cronjob. For testing purposes I wrote a function that sends me an email every hour, but it’s not working.
I’ve got a plugin called ‘Core Control’ which shows me all existing Cronjobs – mine is also listed there. There is also a button “Run now”. If I press it, I get the test-mail, so the function itself is correct.
Here is the code for the Cronjob, it is placed inside the functions.php of my theme.
if( !wp_next_scheduled( 'check_cron' ) ) {
wp_schedule_event( time(), 'hourly', 'check_cron' );
}
add_action( 'check_cron', 'sendit' );
function sendit() {
$address = "address@provider.com";
$sender = "Cron_Test";
$sendermail = "crontest@sender.com";
$subject = "It works!";
$text = "Yay, it is working!";
mail($address, $subject, $text, "From: $sender <$sendermail>");
}
There has to be something wrong with the action hook, but I have no idea what’s wrong. Or do I need to place the code in some different file?
Some more Info:
I now that mail();
does not work on localhost, that’s why I created a test blog online. The folder is protected via .htaccess with a password, could that be an issue?
I also checked that my wp-config.php allows Cronjobs.
I also now that the site needs to be visited for the Cronjob to run.
Unfortunately the WordPress cron jobs are only triggered when your site is visited (see Codex):
I believe this to get around the fact that many on shared hosting aren’t normally allowed to set up cron jobs (at least, not without contacting their host first).