echo value from ‘select’ field type into page template using cmb2?

For starters, I recommend you use the API for register metaboxes and fields which can be seen here: https://github.com/WebDevStudios/CMB2/wiki/Basic-Usage#create-a-metabox. To echo the select option’s label, you would do something like this:

add_action( 'cmb2_admin_init', 'custom_metabox' );

function custom_metabox() {
    $cmb = new_cmb2_box( array(
        'id'           => REALIA_PROPERTY_PREFIX . 'ficha_tecnica',
        'title'        => 'Ficha Técnica',
        'object_types' => array( 'property' ),
    ) );

    $cmb->add_field( array(
        'id'   => REALIA_PROPERTY_PREFIX . 'area_terreno',
        'name' => 'Área do Terreno',
        'type' => 'text'
    ) );

    $cmb->add_field( array(
        'id'               => 'wiki_test_select',
        'name'             => 'Test select inline',
        'type'             => 'select',
        'show_option_none' => true,
        'default'          => 'custom',
        // Use an options callback
        'options_cb'       => 'wiki_test_select_options',
    ) );

}

function wiki_test_select_options() {
    // return a standard options array
    return array(
         'standard' => __( 'test123', 'ficha' ),
         'custom'   => __( 'test1234', 'ficha' ),
         'none'     => __( 'test12345', 'ficha' ),
    );
}

And then in the theme:

<?php
$metafield_id = get_the_ID();
$options = wiki_test_select_options();
$key = get_post_meta( $metafield_id, 'wiki_test_select', true );
$option_name = isset( $options[ $key ] ) ? $options[ $key ] : $options['custom'];
?>
<dt><?php echo $option_name; ?></dt><dd><?php echo $key; ?></dd>

Leave a Comment