How To Make a Custom Field For CMB2

CMB2 is pretty much the best. It makes it super easy to add fields all over your site and it comes with a ton of useful fields by default. There are also a ton of community made fields out there for extending it with even more functionality!

Sometimes though you need something very specific–a field that doesn’t fit in with any of the fields built into CMB2. Don’t abandon hope; adding new field types to CMB2 is super simple! There are really only two things you need to define for any custom field: what the actual field markup is and how the data is saved. Luckily, CMB2 provides two easy hooks to give you this power!

Make the Field

To define your field markup, you need to hook into the ‘cmb2_render_{field-type}’ action. Let’s say we want to make a field with an input box for first and last names; we’ll call it a ‘human_name’ field. Based on that, our action to hook into is ‘cmb2_render_human_name’.

function cmb2_render_human_name( $field, $escaped_value, $object_id,
          $object_type, $field_type_object ) {

  echo $field_type_object->input( array( 'type' => 'text' ) );
add_action( 'cmb2_render_human_name', 'cmb2_render_human_name', 10, 5 );

As you can see, using CMB2’s built in field creation methods makes it incredibly simple to build your own fields.

Save the Data

Now that we have the markup, we need to do something with the data from the field when it is submitted. While our previous function was just outputting a basic input field, here I want to do a bit of checking to make sure the value given matches up with the format we expect.

function cmb2_sanitize_human_name( $override_value, $value ) {
  $value = sanitize_text_field( $value );

  $names = explode(' ', $value);

  if ( count( $names ) < 2 ) {
    return '';

  return ucwords( $value );
add_filter( 'cmb2_sanitize_human_name', 'cmb2_sanitize_human_name', 10, 2 );

First, I sanitize the field to prevent any issues with malicious inputs, then I split it up into words and confirm that there are at least two names given, and finally I run the string the ucwords which capitalizes the first letter of each word to make it a bit prettier!

More Info

This was a super basic rundown of adding your own fields to CMB2, but you can also add onto this with custom CSS and JS for more complex field behaviors, more complex custom field markup, and a lot more. Take a look at the CMB2 documentation about creating fields for more info!

Have a comment?

Your email address will not be published. Required fields are marked *