Skip to content

Instantly share code, notes, and snippets.

@kreativan
Created May 19, 2024 19:26
Show Gist options
  • Save kreativan/4c8777701c53852de7ff488d30747c10 to your computer and use it in GitHub Desktop.
Save kreativan/4c8777701c53852de7ff488d30747c10 to your computer and use it in GitHub Desktop.
Wordpress Cron Job
<?php
namespace Kreativan;
if (!defined('ABSPATH')) {
exit;
}
class CronJob {
public function __construct($plugin_file) {
// Schedule the event when the plugin/theme is activated
register_activation_hook($plugin_file, [$this, 'activate']);
// Schedule the event when the plugin/theme is deactivated
register_deactivation_hook($plugin_file, [$this, 'deactivate']);
// Schedule the cron job when the class is instantiated
add_action('init', [$this, 'schedule_cron_job']);
// Hook into the action to execute the cron job
add_action('my_custom_job', [$this, 'my_custom_function']);
}
public function my_custom_function() {
// Do Something
}
// Schedule the cron job
public function schedule_cron_job() {
if (!wp_next_scheduled('my_custom_job')) {
wp_schedule_event(time(), 'weekly', 'my_custom_job');
}
}
// Activate the cron job
public function activate() {
$this->schedule_cron_job();
}
// Deactivate the cron job
public function deactivate() {
wp_clear_scheduled_hook('my_custom_job');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment