Skip to content

Instantly share code, notes, and snippets.

@AnadarProSvcs
Last active December 2, 2023 18:53
Show Gist options
  • Save AnadarProSvcs/d450eff1964c6f41a2a22414fc251fc4 to your computer and use it in GitHub Desktop.
Save AnadarProSvcs/d450eff1964c6f41a2a22414fc251fc4 to your computer and use it in GitHub Desktop.
Adding a cron job to a WordPress plug-in
// When the plugin is activated, schedule a weekly event for a specific task
function custom_plugin_activate() {
// Check if the event isn't already scheduled
if (!wp_next_scheduled('custom_task_hook')) {
// Schedule a weekly event using WordPress cron
wp_schedule_event(time(), 'weekly', 'custom_task_hook');
}
// Call the function to perform the task immediately upon activation
perform_custom_task();
}
// Hook the function to plugin activation
register_activation_hook(__FILE__, 'custom_plugin_activate');
// Function to be executed by the cron job
function perform_custom_task() {
// Include the required file for performing the task
require_once(plugin_dir_path(__FILE__) . 'cron/custom_task_file.php');
// Call the function that handles the task
execute_custom_task();
}
// Hook the custom task function to the custom action
add_action('custom_task_hook', 'perform_custom_task');
// When the plugin is deactivated, remove the scheduled event
function custom_plugin_deactivate() {
// Get the timestamp of the next scheduled event
$timestamp = wp_next_scheduled('custom_task_hook');
// Unschedules the event
wp_unschedule_event($timestamp, 'custom_task_hook');
}
// Hook the function to plugin deactivation
register_deactivation_hook(__FILE__, 'custom_plugin_deactivate');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment