如何在WordPress Cron任务函数中传递参数?
解决WordPress Cron任务无法接收表单提交的$post_id问题
问题根源
Cron任务是WordPress后台独立运行的进程,不会保留表单请求中的$post_id变量。你当前的代码在调度事件时没有传递参数,导致update_my_post函数执行时$post_id未定义,自然无法正常工作。
修复步骤
1. 调整表单提交逻辑顺序
先获取表单中的$post_id,再判断是否需要调度Cron事件,避免调度时变量未赋值:
if(isset( $_POST['btnaup'])) { $post_id = $_POST['id']; $b = $_POST['days']; // 先获取参数,再判断是否调度事件 if(!empty($_POST) && !wp_next_scheduled( 'update_post', array($post_id) )) { wp_schedule_event( time(), 'one_minute', 'update_post', array($post_id) ); } }
2. 确保钩子正确接收参数
注册钩子时已指定接受1个参数(第4个参数1),回调函数需保证能正确接收;后续若要取消事件,必须使用相同参数。
3. 完整修正代码
// 添加自定义Cron调度间隔 function cron_add_one_minute( $schedules ) { $schedules['one_minute'] = array( 'interval' => 60, 'display' => '每分钟一次' ); return $schedules; } add_filter('cron_schedules', 'cron_add_one_minute'); // 处理表单提交 if(isset( $_POST['btnaup'])) { $post_id = intval($_POST['id']); // 转整数避免安全风险 $b = $_POST['days']; // 检查是否已存在相同参数的调度事件 if(!wp_next_scheduled( 'update_post', array($post_id) )) { // 调度事件时传递$post_id作为参数 wp_schedule_event( time(), 'one_minute', 'update_post', array($post_id) ); } } // 注册Cron钩子,指定接受1个参数 add_action( 'update_post', 'update_my_post', 10, 1); // Cron回调函数 function update_my_post( $post_id ){ // 验证post_id有效性,避免非法值 if(!is_numeric($post_id) || !get_post($post_id)) { return; } $time = current_time('mysql'); wp_update_post( array ( 'ID' => $post_id, 'post_date' => $time, 'post_date_gmt' => get_gmt_from_date( $time ), 'post_modified' => $time, 'post_modified_gmt' => get_gmt_from_date($time), ) ); // 可选:若只需执行一次,完成后取消调度 wp_clear_scheduled_hook('update_post', array($post_id)); }
额外注意事项
- 安全优化:对
$_POST['id']做intval转换,回调函数中验证$post_id对应真实文章,避免非法值。 - 单次执行需求:如果不需要每分钟重复执行,建议用
wp_schedule_single_event替代wp_schedule_event。 - 调试工具:可使用WP Crontrol插件查看已调度的Cron事件,确认参数是否正确传递。
内容的提问来源于stack exchange,提问作者JackAsmon
相关产品推荐
相关产品推荐

