Tom Geoco
Tom Geoco

Reputation: 815

Why do my custom meta data fields clear after saving?

I've added a custom meta field to my Wordpress post type. Everytime I save, the fields don't hold the information (however the information is saved to the database).

My code:

function add_post_meta() {
    add_meta_box( 
        'my_meta_box',
        __( 'Metabox', 'framework' ),
        'meta_box_content',
        'post_type',
        'advanced',
        'high'
    );
}
add_action( 'add_meta_boxes', 'add_post_meta' );

function virtual_merchant_box_content( $post ) {
    wp_nonce_field( plugin_basename( __FILE__ ), 'meta_box_content_nonce' );

    echo '<table><tr>';
    echo '<td><label for="input_value">Enter Input Value:</label></td>';
    echo '<td><input type="text" id="input_value" name="input_value" /></td>';
    echo '</tr></table>';

}

function meta_box_save( $post_id ) {

   if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
   return;

   if ( !wp_verify_nonce( $_POST['meta_box_content_nonce'], plugin_basename( __FILE__ ) ) )
   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;
   }


   $input_value = $_POST['input_value'];
   update_post_meta( $post_id, 'input_value', $input_value );

}

add_action( 'save_post', 'metat_box_save' );

Upvotes: 1

Views: 177

Answers (1)

Michael Lewis
Michael Lewis

Reputation: 4302

Get the input value using get_post_meta(), and then add it to the value="" attribute of the text input field.

function virtual_merchant_box_content( $post ) {
    wp_nonce_field( plugin_basename( __FILE__ ), 'meta_box_content_nonce' );

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

    echo '<table><tr>';
    echo '<td><label for="input_value">Enter Input Value:</label></td>';
    echo '<td><input type="text" id="input_value" name="input_value" value="' . $input_value . '" /></td>';
    echo '</tr></table>';

}

Upvotes: 1

Related Questions