Normally in WordPress plugin development, we declare a scheduled event like the following.
register_activation_hook( __FILE__, 'my_plugin_activation_event' );
function my_plugin_activation_event() {
if ( ! wp_next_scheduled( 'my_plugin_activation_event' ) ) {
wp_schedule_event( time(), 'daily', 'my_plugin_activation_event' );
}
}
register_deactivation_hook( __FILE__, 'my_plugin_deactivation_event' );
function my_plugin_deactivation_event() {
wp_clear_scheduled_hook( 'my_plugin_deactivation_event' );
}
We use this type of code in many places.
Problem is that - This code is not re-usable.
We can create a class for reuse.
Let's Start
- Create a class or global functions file
a. First create a class name Schedule
namespace MyPlugin\Utilities;
class Scheduler {
}
b. Then add a method name add
public static function add( $hook, $callback, $recurrence = 'daily', $start_time = null ) {
if ( ! wp_next_scheduled( $hook ) ) {
if(!$start_time) $start_time = time();
wp_schedule_event( $start_time, $recurrence, $hook );
}
add_action( $hook, $callback );
}
** $hook
: hook name for the event.
** $callback
: callback function or array for add action of our event hook.
** $recurrence
: How often the event should subsequently recur. See wp_get_schedules() for accepted values. Default id 'daily'
** $start_time
: event first starting time. You can pass your desired time.
c. Then we need to remove/clean our event.
For that let's create a method for removing events.
public static function delete($hook){
wp_clear_scheduled_hook($hook);
}
Uses
Schedule::add('my-custom-schedule-event', [$this, 'event_handler']);
Schedule::delete('my-custom-schedule-event');
OR you can create global functions as like previous methods.
For Creating Awesome Structured PSR Based Plugin:
PluginMaster, a WordPress plugin development framework
Top comments (0)