
当通过 wp_insert_post() 更新已有页面时,WordPress 默认会覆盖 post_date 字段,导致 get_the_date() 返回更新时间而非原始发布时间;本文提供两种可靠方案——改用 wp_update_post() 或显式指定 post_date,确保原始日期不被意外重写。
当通过 `wp_insert_post()` 更新已有页面时,wordpress 默认会覆盖 `post_date` 字段,导致 `get_the_date()` 返回更新时间而非原始发布时间;本文提供两种可靠方案——改用 `wp_update_post()` 或显式指定 `post_date`,确保原始日期不被意外重写。
在 WordPress 开发中,wp_insert_post() 是一个功能强大但行为严谨的函数:当传入有效的 'ID' 参数时,它本质上执行的是“更新”操作,但默认会将 post_date 和 post_date_gmt 重置为当前时间——这正是导致 get_the_date() 显示错误日期的根本原因。而 get_the_modified_date() 则始终反映最后一次数据库写入时间(包括 wp_insert_post() 调用),因此两者在模板中对比失效。
✅ 推荐方案一:优先使用 wp_update_post()
wp_update_post() 是专为更新设计的封装函数,它自动保留原始 post_date 和 post_date_gmt,仅更新显式传入的字段,语义清晰且更安全:
$updated_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_parent' => $parent_page,
'comment_status'=> 'open'
);
$pid = wp_update_post($updated_post);
// 验证是否成功(返回 0 或 WP_Error 表示失败)
if (is_wp_error($pid)) {
error_log('Page update failed: ' . $pid->get_error_message());
}⚠️ 注意:
wp_update_post()不接受'post_type'参数(类型由 ID 对应的现有文章决定),也不支持'post_date'覆盖——这恰恰是其优势:杜绝误覆写原始时间。
✅ 方案二:在 wp_insert_post() 中显式恢复原始日期
若必须使用 wp_insert_post()(例如需兼容特定逻辑),则需手动读取并传入原始 post_date 和 post_date_gmt:
// 先获取原始文章数据
$original_post = get_post($postId);
if (!$original_post || $original_post->post_type !== 'page') {
wp_die('Invalid page ID');
}
$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);? 模板层验证:确保显示逻辑健壮
你的模板代码本身正确,但建议增强鲁棒性(如避免时间比较失败):
<?php
$original_date = get_the_date('Y-m-d H:i:s'); // 获取格式化原始日期
$modified_date = get_the_modified_date('Y-m-d H:i:s');
// 安全比较:确保两者均为有效时间戳
if ($modified_date && $original_date && strtotime($modified_date) > strtotime($original_date)) :
?>
<span class="edited">(last edited <?php echo esc_html(get_the_modified_date()); ?>)</span>
<?php endif; ?>✅ 总结
- ❌ 避免对已有文章 ID 直接调用
wp_insert_post()而不指定post_date—— 这会无意覆盖历史时间戳; - ✅ 优先选用
wp_update_post(),语义明确、行为可预期; - ✅ 若必须用
wp_insert_post(),务必通过get_post()提前读取并显式传入post_date与post_date_gmt; - ? 始终校验
$pid返回值,并在模板中做时间有效性判断,提升代码健壮性。
遵循以上实践,即可确保无论通过后台编辑还是程序化更新,页面的“原始发布日期”始终准确呈现。

















