This is first time that I tried the OOP method of writing an application. I don’t quite understand it yet. Currently I have this cron hook:
if( !wp_next_scheduled( 'my_cron_hook' ) ) {
//schedule the event to run daily
wp_schedule_event( current_time( 'timestamp' ), 'daily', 'my_cron_hook' );
}
add_action('my_cron_hook',array($this,'do_daily_job'));
It seems that it can’t use if
within a class directly. Do I need to put the entire code above into the __construct()
function?
Also, I found this in WordPress wp_schedule_event
documentation.
function my_activation() {
if ( !wp_next_scheduled( 'my_hourly_event' ) ) {
wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
}
}
add_action('wp', 'my_activation');
What dose ‘wp’ hook here means? I have never seen this in the hook API. Should I wrapped my cron code (above) in a function and put this ‘wp’ action in the __construct()
function, like this?
function __construct() {
add_action('wp', array($this,'my_activation'));
}
function my_activation() {
if( !wp_next_scheduled( 'my_cron_hook' ) ) {
//schedule the event to run daily
wp_schedule_event( current_time( 'timestamp' ), 'daily', 'my_cron_hook' );
}
add_action('my_cron_hook',array($this,'do_daily_job'));
}
Add an action outside your class definition:
And then use this in your event:
You could create a function in your class and call the hook in your constructor. The code below which is similar to what you showed. If you create this into a plugin, you could instantiate your class upon activation and create your cron job. In addition to the code below, here’s a good link on Cron Jobs in PHP Managing Cron Jobs in PHP
PHP will throw a syntax error if you try to put an if-statement directly inside a class – the only things that can go between those curly brackets are variable declarations (eg
public $foo
) and functions (egfunction bar(){ /*stuff*/}
).It’s absolutely fine to set the job from a class constructor – or indeed any other function in the class. Just make sure you actually instantiate the class (and call the necessary function, if it’s not in the constructor) in time for the hook to be added.
To put it briefly, WP is a hook that fires when the whole thing is loaded, all the posts fetched etc, but before templates are loaded.
Some will argue that the best way to register a cron job is to attach it to an activation hook. This is a hook that’s only fired when the plugin is first activated. Otherwise you run the risk of registering the same job more than once, which has obvious drawbacks. That’s what the code from the codex you include is for – to check it hasn’t already been scheduled. That’s one way of doing it, this is another.
Before the main class begin (eg in your base plugin.php file with the header info at the top), your code should look something like
Obviously if you de- and re-activate the plugin this may cause trouble.