0

I am building a website using Wordpress in where I want to show the Metadata from the custom fields. I have setup the cmb2 in my function.php as like below the codes..

add_action( 'cmb2_admin_init', 'cmb2_sample_metaboxes' );

function cmb2_sample_metaboxes() {

    
    $cmb = new_cmb2_box( array(
        'id'            => 'test_metabox',
        'title'         => __( 'Test Metabox', 'cmb2' ),
        'object_types'  => array( 'page', ), 
        'context'       => 'normal',
        'priority'      => 'high',
        'show_names'    => true, 
        
    ) );

    
    $cmb->add_field( array(
        'name'       => __( 'Test Text', 'cmb2' ),
        'desc'       => __( 'field description (optional)', 'cmb2' ),
        'id'         => 'yourprefix_text',
        'type'       => 'text',
        'show_on_cb' => 'cmb2_hide_if_no_cats', 
        
        
        
    ) );

}

Ok, that is working in the post section, That's working. But when I tried to show Metadata in the front-end using

<?php

$text = get_post_meta( get_the_ID(), '_yourprefix_text', true );


echo esc_html( $text );
?>

nothing is echoing.

Anyone please find out what the problems are.

wecade7130
  • 13
  • 3

1 Answers1

0

Looks like you've just got a typo. The id does not match the meta_key: 'yourprefix_text' vs '_yourprefix_text'

Fixed:

<?php

$text = get_post_meta( get_the_ID(), 'yourprefix_text', true );


echo esc_html( $text );
?>
  • that what i find in the documentation – wecade7130 Sep 16 '20 at 00:53
  • CMB2 is not the problem. The reason why nothing is echoing is simply that you store a post_meta field called ''yourprefix_text' but want to get the value from a post_meta field called '_yourprefix_text'. The ID in add_field() is not the same as the parameter meta_key in get_post_meta(). But it has to be exactly the same. Change '_yourprefix_text' to 'yourprefix_text' and it will echo. :-) – nickless Sep 16 '20 at 17:16