Search code examples
wordpresscustom-post-typemeta-boxes

Custom Meta Boxes in Wordpress are not updating - need help identifying the errors in this function


I created a small plugin to add a Color meta box to a custom post type. The box displays fine but I can't seem to get it to save the data. When I type something in the field and click update, the field returns blank. I researched this and followed many tutorials, and each offered a slightly different approach. The code below was the easiest for me to follow, so I would really appreciate any help with identifying the error(s) in it. This is my first question so sorry if I omitted anything relevant.

Here is how I added the box:

add_action( 'add_meta_boxes', 'addmeta' );
function addmeta() {
    $post_types = array ('post', 'ev');

    foreach ( $post_types as $post_type ) {
        add_meta_box (
        'color_box',
        'Color',
        'display_meta_box',
        $post_type,
        'side'
        );
    }
}

add_action ( 'add_meta_boxes', 'addmeta');

Function to display the meta box:

function display_meta_box() {

    $value = get_post_meta( $post->ID, '_mykey', true);

    wp_nonce_field( basename( __FILE__ ), 'my_nonce' );

    ?>

<label for="color_box"><strong>Color:</strong> </label>
<input type="text" name="my_text" id="my_text" />

    <?php

}

And this is the save function:

function save_meta_box ( $post_id ) {

    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );

    $wp_valid_nonce = false;

    if( isset( $_POST[ 'my_nonce' ] ) ) {

        if ( wp_verify_nonce( $_POST['my_nonce'], basename( __FILE__ ) ) ) {

            $is_valid_nonce = true;

        }

    }

    if ( $is_autosave || $is_revision || !$is_valid_nonce ) return;

    if( array_key_exists( 'color_box', $_POST ) ) {

        update_post_meta(
            $post_id,
            '_mykey',
            sanitize_text_field( $_POST[ 'color_box' ] )
        );

    }

}

add_action( 'save_post', 'save_meta_box' );

Thank you!


Solution

  • you need to define ID. Check this code it will work definitively.

    function display_meta_box( ) {
    
    
        $value = get_post_meta( get_the_ID(), '_mykey', true);
    
        wp_nonce_field( basename( __FILE__ ), 'my_nonce' );
    
        ?>
    
    <label for="color_box"><strong>Color:</strong> </label>
    <input type="text" name="color_box" value="<?php echo $value;?>" id="my_text" />
    
        <?php
    
    }