The Events Calendar中tribe_get_event()返回日期异常问题求助
问题分析与解决方案
出现January 1st, 1970(Unix时间戳0对应的日期),说明strtotime()解析日期字符串失败,返回了false。结合你的代码和环境差异,问题根源及解决思路如下:
核心问题
错误访问活动日期属性
$event->start_date并非WP_Post对象的原生属性,The Events Calendar的活动日期实际存储在自定义字段(post meta)中。开发环境中可能因调试模式、对象重载机制让直接访问生效,但生产环境无法正确获取值,导致传入strtotime的是空值或无效字符串。tribe_get_start_date使用不当
调用tribe_get_start_date($event)时未指定格式参数,默认返回网站本地化的日期字符串(如“2024年5月20日”),这类字符串在不同locale环境下无法被strtotime正确解析,尤其生产环境的语言/时区设置与开发环境不一致时。
解决方法
1. 正确获取时间戳(推荐)
使用The Events Calendar提供的参数直接获取Unix时间戳,避免手动解析字符串:
public function setEvent(?\WP_Post $event): self { if (! $event) { return $this; } $this->eventTitle = $event->post_title; // 获取起始日期的Unix时间戳,无需strtotime转换 $start_timestamp = tribe_get_start_date($event, true, 'U'); $this->eventDate = date('F jS, Y', $start_timestamp); $this->eventPermalink = get_permalink($event); return $this; }
- 第二个参数
true表示基于GMT时区(可根据需求改为false使用站点时区) - 第三个参数
'U'指定返回Unix时间戳,彻底避免字符串解析问题
2. 直接读取自定义字段
若上述方法仍有问题,可直接读取活动的原始日期字段:
public function setEvent(?\WP_Post $event): self { if (! $event) { return $this; } $this->eventTitle = $event->post_title; // 读取存储的原始日期字符串 $start_date_raw = get_post_meta($event->ID, '_EventStartDate', true); $start_timestamp = strtotime($start_date_raw); // 处理解析失败的情况 $this->eventDate = $start_timestamp ? date('F jS, Y', $start_timestamp) : '日期待定'; $this->eventPermalink = get_permalink($event); return $this; }
3. 统一时区配置
确保开发与生产环境的时区设置一致:
- PHP:修改
php.ini中的date.timezone参数(如date.timezone = Asia/Shanghai) - WordPress:后台「设置」→「常规」中设置相同时区
- MySQL:执行
SET time_zone = 'Asia/Shanghai';调整时区
4. 调试验证(开发环境用)
添加日志输出确认日期值是否正确:
// 开发环境调试,生产环境需注释 error_log('Event ID: ' . $event->ID); error_log('Raw start date from meta: ' . get_post_meta($event->ID, '_EventStartDate', true)); error_log('tribe_get_start_date with timestamp: ' . tribe_get_start_date($event, true, 'U'));
内容的提问来源于stack exchange,提问作者mpemburn
相关产品推荐
相关产品推荐

