Skip to content

Adding your own field types

joehoyle edited this page Nov 17, 2012 · 14 revisions

To add your own field type you must extend the base class CMB_Field and implement some methods. Primarily you will need to add the html() method which is responsible for outputting a single copy of 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
    }

}

There are several other methods you can implement, for example if you field needs extra JavaScript or CSS you can wp_enqueue_script / wp_enqueue_script by implementing enqueue_scripts and enqueue_styles respectively. See https://github.com/humanmade/Custom-Meta-Boxes/blob/master/classes.fields.php#L688 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 );
    }

}