如何在WordPress中创建每日运行3次的Cron任务实现角色与帖子更新
WordPress自动处理Pro Property过期的Cron任务实现
一、注册自定义Cron间隔与任务
先给WordPress添加自定义Cron运行间隔(按每日4次设置,即每6小时一次),再注册对应的Cron事件和处理钩子:
// 添加自定义Cron时间间隔 add_filter('cron_schedules', 'add_property_expiry_cron_interval'); function add_property_expiry_cron_interval($schedules) { $schedules['every_6_hours'] = array( 'interval' => 21600, // 6小时换算为秒 'display' => __('每6小时运行一次') ); return $schedules; } // 注册Cron事件 add_action('wp', 'register_property_expiry_cron'); function register_property_expiry_cron() { if (!wp_next_scheduled('property_expiry_check_event')) { wp_schedule_event(time(), 'every_6_hours', 'property_expiry_check_event'); } } // 绑定事件到处理函数 add_action('property_expiry_check_event', 'handle_property_expiry');
二、核心过期处理逻辑
以下代码完成帖子检查、用户角色更新、帖子元数据与术语修改的完整逻辑:
function handle_property_expiry() { // 确保日期格式和你存储的expiry_date一致,这里用Y-m-d为例 $current_date = date('Y-m-d'); // 查询所有过期的properties帖子 $args = array( 'post_type' => 'properties', 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'expiry_date', 'value' => $current_date, 'compare' => '=', 'type' => 'DATE' ) ), 'tax_query' => array( array( 'taxonomy' => 'your_property_taxonomy', // 替换为你的自定义分类法slug 'field' => 'name', 'terms' => 'Pro Property' ) ) ); $expired_posts = new WP_Query($args); if ($expired_posts->have_posts()) { while ($expired_posts->have_posts()) { $expired_posts->the_post(); $post_id = get_the_ID(); $author_id = get_the_author_meta('ID'); // 1. 移除帖子的「Pro Property」术语 wp_remove_object_terms($post_id, 'Pro Property', 'your_property_taxonomy'); // 2. 删除expiry_date元字段 delete_post_meta($post_id, 'expiry_date'); // 3. 检查该用户是否还有带「Pro Property」的properties帖子 $user_pro_posts = new WP_Query(array( 'post_type' => 'properties', 'posts_per_page' => -1, 'author' => $author_id, 'tax_query' => array( array( 'taxonomy' => 'your_property_taxonomy', 'field' => 'name', 'terms' => 'Pro Property' ) ) )); // 无有效Pro帖子则降级用户角色 if (!$user_pro_posts->have_posts()) { $user = new WP_User($author_id); $user->remove_role('author'); $user->add_role('subscriber'); } } wp_reset_postdata(); } }
三、关键注意事项
- 替换分类法slug:代码中的
your_property_taxonomy要换成你实际使用的自定义分类法标识,也就是创建properties时定义的分类法slug。 - 日期格式统一:如果你的
expiry_date存储的是其他格式,比如d/m/Y,要同步修改$current_date的格式和meta_query里的type参数。 - Cron可靠性优化:WordPress默认Cron依赖用户访问触发,低流量网站可能延迟,建议配置服务器系统Cron:
*/15 * * * * wget -q -O - https://你的域名/wp-cron.php?doing_wp_cron >/dev/null 2>&1 - 测试方法:可临时添加以下代码到主题
functions.php,管理员访问网站即可手动触发测试,测试后删除:add_action('init', function() { if (current_user_can('administrator')) { handle_property_expiry(); echo '过期处理已执行'; exit; } }); - 数据备份:正式部署前务必备份数据库,避免逻辑错误导致数据丢失。
内容的提问来源于stack exchange,提问作者Developer Mohsin
相关产品推荐
相关产品推荐

