doesn't save custom meta box data wordpress

saranganime

Member
Dec 23, 2019
34
8
8
My WP doesn't save my meta box data. I see the metabox and the field, but the data doesn't saving. Somebody could help me? Thank you. This is the code:

PHP:
<?php
// Function to add a metabox
function add_duration_metabox() {
    add_meta_box('duration_metabox', 'Duration', 'display_duration_metabox', 'post', 'normal', 'high');
}

// Function to display the content within the metabox
function display_duration_metabox($post) {
    // Retrieve the current value from the database if it exists
    $duration = get_post_meta($post->ID, 'duration', true); // Change _duration to duration
    $duration = intval($duration); // Ensure it's an integer

    // Separate hours, minutes, and seconds
    $hours = floor($duration / 3600);
    $minutes = floor(($duration % 3600) / 60);
    $seconds = $duration % 60;

    // Display input fields for hours, minutes, and seconds
    ?>
    <label for="hours">Hours:</label>
    <input type="number" id="hours" name="hours" value="<?php echo esc_attr($hours); ?>" min="0" />

    <label for="minutes">Minutes:</label>
    <input type="number" id="minutes" name="minutes" value="<?php echo esc_attr($minutes); ?>" min="0" max="59" />

    <label for="seconds">Seconds:</label>
    <input type="number" id="seconds" name="seconds" value="<?php echo esc_attr($seconds); ?>" min="0" max="59" />
    <?php
}

// Function to save the value to the database
function save_duration_metabox($post_id) {
    // Check if the nonce is set
    if (!isset($_POST['duration_nonce'])) {
        return $post_id;
    }

    // Verify the nonce
    if (!wp_verify_nonce($_POST['duration_nonce'], 'save_duration')) {
        return $post_id;
    }

    // If this is an autosave, ignore it
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }

    // Get hours, minutes, and seconds from input fields and ensure they are integers
    $hours = isset($_POST['hours']) ? intval($_POST['hours']) : 0;
    $minutes = isset($_POST['minutes']) ? intval($_POST['minutes']) : 0;
    $seconds = isset($_POST['seconds']) ? intval($_POST['seconds']) : 0;

    // Calculate the total duration in seconds
    $duration = ($hours * 3600) + ($minutes * 60) + $seconds;

    // Save the duration value to the database with the name 'duration' instead of '_duration'
    update_post_meta($post_id, 'duration', sanitize_text_field($duration)); // Change _duration to duration
}

// Add the metabox
add_action('add_meta_boxes', 'add_duration_metabox');

// Save the value to the database
add_action('save_post', 'save_duration_metabox');
 

Attachments

  • Screenshot_1.png
    Screenshot_1.png
    3.9 KB · Views: 1

Forum statistics

Threads
73,713
Messages
1,030,446
Members
232,239
Latest member
aaaaaaaaaxd xc v