为什么需要自动更新文章时间
在WordPress网站运营过程中,我们经常遇到需要修改已发布文章内容的情况。默认情况下,WordPress只会在文章首次发布时记录发布时间,后续修改不会改变这个时间戳。这可能会导致以下问题:
- 读者无法直观了解文章最后更新时间
- 搜索引擎可能无法识别内容的新鲜度
- 按时间排序的内容可能无法反映最新修改
使用自定义函数解决方案
通过向WordPress主题的functions.php文件添加自定义函数,我们可以实现文章修改时自动更新时间戳的功能。以下是实现这一需求的完整代码方案:
/**
* 自动更新文章修改时间
* 当文章内容更新时,自动将修改时间设置为当前时间
*/
function auto_update_post_modified_time( $post_id ) {
// 自动保存时不执行
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return;
// 检查用户权限
if ( !current_user_can('edit_post', $post_id) )
return;
// 更新文章修改时间
$post_data = array(
'ID' => $post_id,
'post_modified' => current_time('mysql'),
'post_modified_gmt' => current_time('mysql', 1)
);
// 移除钩子避免无限循环
remove_action('save_post', 'auto_update_post_modified_time');
// 更新文章
wp_update_post( $post_data );
// 重新添加钩子
add_action('save_post', 'auto_update_post_modified_time');
}
add_action( 'save_post', 'auto_update_post_modified_time' );
代码功能解析
防止自动保存触发:通过检查DOING_AUTOSAVE常量,避免自动保存操作触发时间更新
权限验证:确保只有有编辑权限的用户能够触发此功能
时间更新:使用current_time()函数获取当前时间,分别设置本地时间和GMT时间
防止无限循环:在更新文章前暂时移除钩子,更新完成后再重新添加,避免save_post动作的递归调用
进阶优化方案
如果需要更精细的控制,可以考虑以下扩展功能:
/**
* 增强版文章时间自动更新
* 可控制特定文章类型,添加自定义时间格式
*/
function enhanced_auto_update_post_time( $post_id ) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return;
if ( !current_user_can('edit_post', $post_id) )
return;
// 只对post类型文章生效
$post_type = get_post_type($post_id);
if ('post' != $post_type)
return;
// 获取文章对象
$post = get_post($post_id);
// 如果文章未发布,则不处理
if ('publish' != $post->post_status)
return;
// 更新时间和修改时间
$post_data = array(
'ID' => $post_id,
'post_modified' => current_time('mysql'),
'post_modified_gmt' => current_time('mysql', 1),
// 可选:同时更新发布时间
// 'post_date' => current_time('mysql'),
// 'post_date_gmt' => current_time('mysql', 1)
);
remove_action('save_post', 'enhanced_auto_update_post_time');
wp_update_post( $post_data );
add_action('save_post', 'enhanced_auto_update_post_time');
// 可选:添加自定义元数据记录修改历史
$edit_count = get_post_meta($post_id, '_edit_count', true);
$edit_count = $edit_count ? $edit_count + 1 : 1;
update_post_meta($post_id, '_edit_count', $edit_count);
update_post_meta($post_id, '_last_edited', current_time('mysql'));
}
add_action( 'save_post', 'enhanced_auto_update_post_time' );
前台显示优化
实现时间自动更新后,可以在主题模板文件中使用以下代码显示最后修改时间:
$last_modified = get_the_modified_time('Y-m-d H:i:s');
echo '最后更新于:' . $last_modified;
或者使用更友好的相对时间格式:
echo '最后更新:' . human_time_diff(get_the_modified_time('U'), current_time('timestamp')) . '前';
注意事项
- 修改functions.php文件前建议先备份
- 使用子主题进行修改,避免主题更新时丢失自定义功能
- 对于已有文章,可能需要批量更新修改时间
- 某些SEO插件可能会与时间修改功能产生冲突,需要测试兼容性
通过以上方法,您可以轻松实现WordPress文章时间的自动更新功能,确保您的内容始终显示最新的修改时间,提升用户体验和SEO效果。