Search code examples
phpwordpresscustom-post-typeshortcode

Cannot get metadata from database for custom post types


Already tried using save_post and updated_post actions.

Here's the code:

function la_add_custom_metabox() {
add_meta_box(
    'la_meta',
    __( 'Dados de Cadastro' ),
    'la_meta_callback',
    'cota',
    'normal',
    'core'
);
}
add_action( 'add_meta_boxes', 'la_add_custom_metabox' );

My custom field:

function la_meta_callback(){

wp_nonce_field( basename( __FILE__ ), 'la_cotas_nonce' );
$la_stored_meta = get_post_meta( $post->ID ); ?>

<div>

 <div class="meta-row">
   <div class="meta-th">
     <label for="credito" class="dwwp-row-title"><?php _e( 'Crédito',    'la-cotas' ); ?></label>
   </div>
   <div class="meta-td">
    <input type="text" class="dwwp-row-content" name="credito" id="credito" value="<?php if ( ! empty ( $la_stored_meta['credito'] ) ) { echo esc_attr( $la_stored_meta['credito'][0] ); } ?>"/>
   </div>
 </div>
</div>

Function that saves in database

function la_meta_save( $post_id ) {
   // Checks save status
   $is_autosave = wp_is_post_autosave( $post_id );
   $is_revision = wp_is_post_revision( $post_id );
   $is_valid_nonce = ( isset( $_POST[ 'la_cotas_nonce' ] ) && wp_verify_nonce( $_POST[ 'la_cotas_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';

    // Exits script depending on save status
   if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
       return;
   }


    if ( isset( $_POST[ 'credito' ] ) ) {
        update_post_meta( $post_id, 'credito', sanitize_text_field( $_POST[ 'credito' ] ) );
    }

 }

 add_action( 'save_post', 'la_meta_save' );

I tried many tutorials in internet, and i couldn't find what i'm doing wrong.

expected: The data to be inserted in the database and being displayed in the custom edit page field.

Edit 1: I discovered that the data is being saved, but its not being displayed on the edit fields.


Solution

  • Solved: For those who are interested: I wasn't passing $post on the save_meta callback

    //This solved the problem
    function la_meta_callback($post){ ... }