WordPress自定义定时事件不触发 产品浏览量无法定时清零求助
你的代码存在以下几处明显错误:
- 钩子名称不匹配:
wp_next_scheduled()检查的钩子名是hits_set_to_zero,但实际注册定时事件、绑定执行函数用的钩子名是hits_set_zero,二者名称不一致导致定时任务根本不会被触发。 - 定时任务上下文不存在产品对象:Cron任务运行时没有当前产品页的上下文,
global $product无法拿到有效产品对象,就算任务触发也删不掉任何浏览量数据,如果你需要清空所有产品的浏览量,需要遍历查询所有产品ID执行删除。 - 引号语法错误:最后注册定时周期的过滤器
add_filter( ‘cron_schedules’, ‘custom_cron_job_recurrence’ )用了中文全角引号,PHP无法识别会直接抛出语法错误。 delete_post_meta参数使用错误:第三个参数是用来匹配元字段值的,传true只会删除值等于true的元数据,无法正常删除浏览量记录,不需要传该参数。- WP Cron触发机制限制:WordPress原生Cron依赖站点访问触发,若10秒内没有任何人访问站点,定时任务不会准时执行,对时间精度要求高的场景需要替换为系统级定时任务。
修正后的可运行代码
// 记录产品浏览量 add_action('woocommerce_share','setPostViews',70); function setPostViews() { global $product; $product_id = $product->get_id(); // 推荐用WC官方方法获取ID,兼容性更好 $count_key = 'post_views_count'; $count = get_post_meta($product_id, $count_key, true); if($count == ''){ $count = 0; delete_post_meta($product_id, $count_key); add_post_meta($product_id, $count_key, '0'); }else{ $count++; update_post_meta($product_id, $count_key, $count); } echo 'view::'.$count; } // 注册定时任务 add_action( 'wp', 'hits_set_zero_schedule' ); function hits_set_zero_schedule() { if ( ! wp_next_scheduled( 'hits_set_zero' ) ) { // 统一钩子名 wp_schedule_event( time(), '10sec', 'hits_set_zero' ); } } // 定时清空所有产品浏览量 add_action( 'hits_set_zero', 'hits_set_zero_func' ); function hits_set_zero_func() { // 查询所有已发布的产品 $products = get_posts( array( 'post_type' => 'product', 'posts_per_page' => -1, 'post_status' => 'publish', 'fields' => 'ids' // 只查ID减少性能消耗 ) ); foreach ($products as $product_id) { delete_post_meta( $product_id, 'post_views_count' ); // 移除错误的第三个参数 } } // 添加自定义定时周期 add_filter( 'cron_schedules', 'custom_cron_job_recurrence' ); // 改为英文半角引号 function custom_cron_job_recurrence( $schedules ) { if(!isset($schedules['10sec'])) { $schedules['10sec'] = array( 'display' => __( 'Every 10 Seconds', 'twentyfifteen' ), 'interval' => 10, ); } if(!isset($schedules['15sec'])) { $schedules['15sec'] = array( 'display' => __( 'Every 15 Seconds', 'twentyfifteen' ), 'interval' => 15, ); } return $schedules; }
测试说明
替换代码后先清空站点缓存,多刷新几次产品页触发Cron,10秒后再刷新就能看到浏览量重置为1。
内容的提问来源于stack exchange,提问作者mario
相关产品推荐
相关产品推荐

