纯代码WordPress添加二个自定义日期和时间字段匹配WordPress默认格式

在WordPress中,‌默认的日期和时间格式通常遵循PHP的日期和时间函数,‌特别是使用date()time()函数。‌如果你想要在自定义字段中保存与WordPress默认格式相兼容的日期和时间,‌你应该使用这些函数来格式化和保存数据。‌

以下是修改后的代码,‌它将确保自定义字段中的日期和时间以WordPress默认的格式保存:‌

把以下代码放到主题的 functions.php 文件中

/** WordPress添加二个自定义日期和时间字段匹配WordPress默认格式 **/
// 添加自定义日期和时间元框
function add_Exhibition_start_time_meta_box() {
    add_meta_box(
        'Exhibition_start_time_meta_box',
        '自定义日期和时间',
        'render_Exhibition_start_time_meta_box',
        'post',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'add_Exhibition_start_time_meta_box');

// 渲染自定义日期和时间元框的内容
function render_Exhibition_start_time_meta_box($post) {
    wp_nonce_field(basename(__FILE__), 'Exhibition_start_time_nonce');
    $Exhibition_start_time = get_post_meta($post->ID, 'Exhibition_start_time', true);
    $exhibition_end_time = get_post_meta($post->ID, 'exhibition_end_time', true);
    
    // 格式化日期和时间以匹配WordPress默认格式
    $Exhibition_start_time_formatted = $Exhibition_start_time ? date('Y-m-d H:i:s', strtotime($Exhibition_start_time)) : '';
    $exhibition_end_time_formatted = $exhibition_end_time ? date('Y-m-d H:i:s', strtotime($exhibition_end_time)) : '';
    
    echo '<label for="Exhibition_start_time">开展开始日期和时间:</label>';
    echo '<input type="datetime-local" id="Exhibition_start_time" name="Exhibition_start_time" value="' . esc_attr($Exhibition_start_time_formatted) . '" />';
    echo '<label for="exhibition_end_time">展览结束日期和时间:</label>';
    echo '<input type="datetime-local" id="exhibition_end_time" name="exhibition_end_time" value="' . esc_attr($exhibition_end_time_formatted) . '" />';
}

// 保存自定义日期和时间元框的数据
function save_Exhibition_start_time_meta_box_data($post_id) {
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    if (!isset($_POST['Exhibition_start_time_nonce']) || !wp_verify_nonce($_POST['Exhibition_start_time_nonce'], basename(__FILE__))) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    if (isset($_POST['Exhibition_start_time'])) {
        $Exhibition_start_time = sanitize_text_field($_POST['Exhibition_start_time']);
        // 这里不需要再次格式化,‌因为我们已经从表单中接收了格式化的日期时间
        update_post_meta($post_id, 'Exhibition_start_time', $Exhibition_start_time);
    }
    if (isset($_POST['exhibition_end_time'])) {
        $exhibition_end_time = sanitize_text_field($_POST['exhibition_end_time']);
        // 这里同样不需要再次格式化
        update_post_meta($post_id, 'exhibition_end_time', $exhibition_end_time);
    }
}
add_action('save_post', 'save_Exhibition_start_time_meta_box_data');

在这个代码中,‌我已经添加了save_post钩子来确保save_Exhibition_start_time_meta_box_data函数在文章保存时被调用。‌同时,‌在渲染元框内容时,‌我使用了date()函数来格式化已经保存的日期和时间,‌以确保它们以正确的格式显示在表单中。‌然而,‌在保存数据时,‌我们不需要再次格式化,‌因为表单已经以Y-m-d\TH:i的格式(‌这是datetime-local输入类型的格式)‌提供了数据。‌