将其添加到 WordPress 主题的 functions.php 文件中:
function custom_publish_actions() { // 添加复选框到发布元框 echo ' '; // JavaScript 自动更新发布时间 echo '';} function update_post_date_on_publish($data, $postarr) { // 检查复选框是否被勾选并更新发布时间 if (isset($_POST['custom_publish_time_checkbox']) && $_POST['custom_publish_time_checkbox'] == 'yes' && $data['post_status'] == 'publish') { $current_time = current_time('mysql'); $data['post_date'] = $current_time; $data['post_date_gmt'] = get_gmt_from_date($current_time); } return $data;} // 添加动作钩子到发布框add_action('post_submitbox_misc_actions', 'custom_publish_actions');// 添加过滤器以检查复选框状态并更新发布时间add_filter('wp_insert_post_data', 'update_post_date_on_publish', 10, 2);下面是没有可选按钮的版本,更新后即是最新时间。
/** * 在文章更新时,将发布时间修改为当前时间 */function update_post_publish_time_on_save( $post_id ) { // 检查是否启用了自动修订、自动保存,以及用户是否有权限 if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; if ( wp_is_post_revision( $post_id ) ) return; if ( ! current_user_can( 'edit_post', $post_id ) ) return; // 获取当前时间 $current_time = current_time( 'mysql' ); // 获取本地时间 // $current_time_gmt = current_time( 'mysql', 1 ); // 如需使用GMT时间,取消注释此行并替换下一行中的变量 $current_time_gmt = get_gmt_from_date( $current_time ); // 由本地时间转换为GMT时间 // 准备要更新的文章数据 $updated_post_data = array( 'ID' => $post_id, 'post_date' => $current_time, // 更新发布时间(本地时间) 'post_date_gmt' => $current_time_gmt, // 更新发布时间(GMT时间) // 如果你不希望修改修改时间,请明确设置 post_modified 和 post_modified_gmt 为原有的值,但这通常不必要且复杂 // 默认情况下,wp_update_post 会自动更新修改时间 ); // 移除钩子以防止无限循环 remove_action( 'save_post', 'update_post_publish_time_on_save' ); // 更新文章 wp_update_post( $updated_post_data ); // 重新添加钩子 add_action( 'save_post', 'update_post_publish_time_on_save' );}// 将函数挂载到 'save_post' 钩子上,优先级为10,参数数为1add_action( 'save_post', 'update_post_publish_time_on_save', 10, 1 );