WordPress Options on the Front End - rogerlos/cmb2-metatabs-options GitHub Wiki

For this refresher of WordPress basics, imagine we created and saved an options page with a box that had three fields (code removed for clarity!):

// box field ids
$cmb = new_cmb2_box();
$cmb->add_field( array( 'id'  => 'field_1', ));
$cmb->add_field( array( 'id'  => 'field_2', ));
$cmb->add_field( array( 'id'  => 'field_3', ));

// our page
$args = array(
    'key'   => 'my_opts',
    'boxes' => array( $cmb ),
);

On the front end, getting the values saved from your options page is easy:

// WordPress function
$my_options = get_option( 'my_opts' );

my_opts is used by WordPress to save your options to the options table as a single entity (in a serialized array). Because of this, $my_options is an array which contains every field from your options page:

var_dump( $my_options );

// output something like:
array(
    'field_1' => 'Lorem ipsum dolor' (string)
    'field_2' => 'Nonummy' (string)
    'field_3' => 'Howdy!' (string)
)

To display the contents of field_2:

echo $my_options['field_2'];

However! WordPress does not save unchecked check boxes, and it's a good idea in any case to do an isset or empty test on the returned option:

if ( 
    isset( $my_options['field_2'] ) // here we're seeing if the key exists at all
    && $my_options['field_2']       // and here if it has anything inside of it
) {
    echo $my_options['field_2'];
}

If you used a group field, or a repeating field, the returned field will itself be an array:

// my_options field_3 is a repeater
var_dump( $my_options );

// field_3 has a list, accessed via numbered keys:
array(
    'field_1' => 'Lorem ipsum dolor' (string)
    'field_2' => 'Nonummy' (string)
    'field_3' => array(
        0 => 'hello' (string)
        1 => 'howdy' (string)
        2 => 'hola' (string)
    )
)

// my_options field_3 is a group
var_dump( $my_options );

// group field ids are now the keys of the field_3 array:
array(
    'field_1' => 'Lorem ipsum dolor' (string)
    'field_2' => 'Nonummy' (string)
    'field_3' => array(
        0 => array(
            'greeting' => 'hello' (string)
            'use'      => 'formal' (string)
        )
    )
)

The values can be accessed via their keys as well:

echo $my_options['field_3'][0]['greeting'];

In the case of groups or repeaters, you'll probably be using a foreach or other looping to go over the list, which is beyond the scope of this very primitive primer!