save_post
钩子来实现这一功能。以下是一个示例代码,它会在保存文章的时候自动将日期字段设置为当前时间:将上述代码添加到你的WordPress主题的functions.php文件中,或者如果你在编写插件,则将其添加到插件文件中。这段代码会在每次保存文章时检查,如果不是自动保存,并且当前用户有权限编辑文章,就会自动将文章的日期设置为当前时间。
请注意,这段代码没有考虑文章的其他状态,如是否为自动保存(DOING_AUTOSAVE
)、是否为草稿(post_status
为draft
),或是否正在使用某些特定的插件可能会影响这一行为。在实际使用时,你可能需要根据具体情况调整代码。
// 确保此代码在functions.php或插件文件中
// 钩子函数,在保存文章时触发
function auto_update_post_date( $post_id ) {
if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE ) {
return;
}
// 确保当前用户有权限编辑文章
if ( ‘page’ == $_POST[‘post_type’] ) {
if ( !current_user_can( ‘edit_page’, $post_id ) )
return;
} else {
if ( !current_user_can( ‘edit_post’, $post_id ) )
return;
}
// 设置文章的日期为当前时间
$post = get_post( $post_id );
$current_date = current_time( ‘mysql’ );
$post->post_date = $current_date;
wp_update_post( array( ‘ID’ => $post_id, ‘post_date’ => $current_date ) );
}
// 添加钩子
add_action( ‘save_post’, ‘auto_update_post_date’ );
评论(0)