Skip to content

Adding your own field types

Dzikri Aziz edited this page Nov 18, 2015 · 14 revisions

Step 1

To add your own field type you must extend the base class CMB_Field. You must provide the html() method which outputs your field.

Taking an email field as an example:

class Email_Field extends CMB_Field {

    public function html() {
        ?>
        <p>
            <input type="email" name="<?php echo $this->name ?>" value="<?php echo esc_attr( $this->get_value() ) ?>" />
        </p>
        <?php
    }

}

Step 2

Filter cmb_field_types to add your new field. The array key should be the field type, used when adding a field. The array value should be the field class name

add_filter( 'cmb_field_types', function( $cmb_field_types ) {
 	$cmb_field_types['email'] = 'Email_Field';
	return $cmb_field_types;
} );

Step 3

Use this field as normal.

add_filter( 'cmb_meta_boxes', function cmb_sample_metaboxes( array $meta_boxes ) {

    $meta_boxes[] = array(
        'title'    => 'CMB Test - Adding your own field types.',
        'pages'    => 'page',
        'show_on'  => array( 'id' => array( 1 ) ),
        'context'  => 'normal',
        'priority' => 'high',
        'fields'   => array(
            array(
                'id'   => 'example-email-field',
                'name' => 'An example email field',
                'type' => 'email',
            ),
        ),
    );

    return $meta_boxes; 

}

Extra steps.

There are several other methods you can implement, for example if you field needs extra JavaScript or CSS, enqueue these in using the enqueue_scripts and enqueue_styles methods respectively. See https://github.com/humanmade/Custom-Meta-Boxes/blob/master/classes.fields.php#L755 for an example of this.

If you want to adjust a value before it is stored as post meta in your field (for example, convert a local date into UTC) you can implement the parse_save_value() method like so:

class My_Date_Field extends CMB_Field {

    public function html() {
        ?>
        <p>
            <input type="datetime" name="<?php echo $this->name ?>" value="<?php echo esc_attr( $this->get_value() ) ?>" />
        </p>
        <?php
    }

    public function parse_save_value() {
        // adjust $this->value
        $this->value = my_local_time_to_utc( $this->value );
    }

}

If you make any cool useful fields that you want to share, let us know and we can add a link to the Wiki.