You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取通过wp_insert_post修改的页面的原始发布日期?

解决wp_insert_post更新页面时原始发布日期被覆盖的问题

当使用wp_insert_post更新现有页面时,get_the_date()会返回更新后的日期而非原始发布日期,这是因为自定义调用wp_insert_post时,若未显式指定原始发布日期字段,WordPress可能会意外覆盖post_date和post_date_gmt值(后台编辑时系统会自动保留原始日期,但自定义调用需要手动维护)。

解决方案

在构造更新参数数组前,先获取页面的原始发布日期,将post_date和post_date_gmt字段加入到更新数组中,强制保留原始日期。

修改后的代码示例

// 获取原始页面的post对象
$original_post = get_post($postId);
if (!$original_post) {
    // 处理页面不存在的异常情况
    return;
}

$new_post = array(
    'ID'             => $postId,
    'post_name'      => $slug,
    'post_title'     => $title,
    'post_excerpt'   => $excerpt,
    'post_content'   => $description,
    'tags_input'     => explode(',', $_POST['post_tags']),
    'page_template'  => $template_page,
    'post_status'    => 'publish',
    'post_type'      => 'page',
    'post_parent'    => $parent_page,
    'comment_status' => 'open',
    // 加入原始发布日期字段,防止被覆盖
    'post_date'      => $original_post->post_date,
    'post_date_gmt'  => $original_post->post_date_gmt
);

$pid = wp_insert_post($new_post);

效果验证

更新完成后,页面模板中的get_the_date()会正常返回原始发布日期,get_the_modified_date()返回本次更新的日期,显示效果与后台编辑一致:
Posted by User on April 6, 2022 (last edited August 24, 2022)

另外,也可以直接在模板中通过get_post_field('post_date', get_the_ID())获取原始日期,但更推荐从更新逻辑上确保日期不被修改,从根源解决问题。

内容的提问来源于stack exchange,提问作者Paul Lovell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:48:10