我正在开发一个简单的自定义 WordPress 插件,旨在使用 WP Cron 计划任务每 30 分钟自动提交一份重力表格。但是,该插件似乎没有按预期工作,因为表单没有自动提交。
添加自定义 Cron 计划每 30 分钟运行一次。
使用 Gravity Forms API 提交包含预定义数据的特定表单。
记录任何成功或错误消息以进行调试。
这是我完整的插件代码文件:
<?php
/*
Plugin Name: Auto Submit Form Every 30 Minutes
Description: A simple plugin to auto-submit a specific Gravity Form every 30 minutes.
Version: 1.0
Author: Your Name
*/
// Prevent direct access to the file
if (!defined('ABSPATH')) {
exit;
}
// Add a new cron schedule for every 30 minutes
add_filter('cron_schedules', 'asf_add_half_hour_schedule');
function asf_add_half_hour_schedule($schedules) {
$schedules['half_hour'] = array(
'interval' => 1800, // 30 minutes in seconds
'display' => __('Every 30 Minutes')
);
return $schedules;
}
// Function to auto-submit the form
function asf_auto_submit_form() {
$form_id = 1; // ID of the form to submit
// Form data as an array, with field IDs as keys
$form_data = [
1 => 'User Name', // Example data for field ID 1
2 => '[email protected]', // Example data for field ID 2
3 => 'Sample description' // Example data for field ID 3
];
// Submit form using Gravity Forms API
$result = GFAPI::submit_form($form_id, $form_data);
if (is_wp_error($result)) {
error_log('Form submission error: ' . $result->get_error_message());
} else {
error_log('Form submitted successfully! Entry ID: ' . $result['entry_id']);
}
}
// Schedule the cron job if not already scheduled
function asf_schedule_auto_submit() {
if (!wp_next_scheduled('asf_auto_submit_form_event')) {
wp_schedule_event(time(), 'half_hour', 'asf_auto_submit_form_event');
}
}
add_action('wp', 'asf_schedule_auto_submit');
// Hook cron event to form submission function
add_action('asf_auto_submit_form_event', 'asf_auto_submit_form');
// Clear the scheduled task when the plugin is deactivated
function asf_clear_scheduled_auto_submit() {
wp_clear_scheduled_hook('asf_auto_submit_form_event');
}
register_deactivation_hook(__FILE__, 'asf_clear_scheduled_auto_submit');
什么可能导致此问题?
如何进一步调试?
请尝试
init
瞬间wp
add_action('init', 'asf_schedule_auto_submit');
也许这会有帮助。