Intro to CMB2

Benjamin Turner

https://passionsplay.com

https://github.com/bgturner

@passionsplay

https://cmb2.io/

https://wordpress.org/plugins/cmb2/

https://github.com/CMB2/CMB2

An Example Plugin using CMB2

What are Custom Fields?

Custom fields are arbitrary meta data that we can assign to a post.

This data is in the form of a key / value pair.

So for example, if we wanted to record the name of the book we are currently reading when we are writing a specific post, we might:

  • Assign the value of
    Alice in Wonderland
  • To the key of
    currently_reading

WordPress allows us to do this out of the box.

Example of the default custom fields editor in WordPress

Note that WordPress uses 'Name' here instead of 'Key'

If that metabox isn't displayed, you might have to enable it by checking "Custom Fields" from the "Screen Options" button toward the top of the "edit post screen".

Example of the default custom fields editor in WordPress

There are limitations

It's only text input.

Who really wants to hand enter something like location?

US Bancorp Tower

  • Lat: 45.5123103
  • Long: -122.6686434
Finding the latitude and longitude for the Us Bancorp Building in PDX.

It doesn't show all of the custom fields for a post (i.e. things prefixed with an underscore).

Displaying the hidden custom fields

There are a lot of plugins that work with custom fields

https://wordpress.org/search/custom+fields

Searching WordPress.org for custom fields plugins

Why CMB2?

  • Free and Open Source (GPLv2)
  • Easy to extend to create new custom fields
  • Data Portability. The data still exists, and is available on the front end if CMB2 is disabled
  • Configuration is in the code (and therefore is easier to share and merge changes across a team during development)

So what does CMB2 actually do?

Nothing out of the box.

You have to write the code describing the kinds of meta fields you want.

Hook into CMB2 with a custom function


add_action( 'cmb2_admin_init', 'register_metabox' );
function register_metabox() {
	$prefix = 'yourprefix_demo_';
	// Define Custom Fields
}
						

Create a new Metabox to attach our custom fields to


$cmb_demo = new_cmb2_box( array(
	'id'            => $prefix . 'metabox',
	'title'         => esc_html__( 'Test Metabox', 'cmb2' ),
	'object_types'  => array( 'page' ), // Post type
) );						
						

Add field(s) to the previously created Metabox


$cmb_demo->add_field( array(
	'name' => esc_html__( 'Test Text', 'cmb2' ),
	'desc' => esc_html__( 'field description (optional)', 'cmb2' ),
	'id'   => $prefix . 'text',
	'type' => 'text',
) );						
						

Which gives us

The above metabox rendered on a WordPress page.

There are lots of additional fields included with the default CMB2 plugin.

  • URL
  • Date
  • ColorPicker
  • File Upload
  • oEmbed
  • More!

https://github.com/CMB2/CMB2/wiki/Field-Types#types

Installing CMB2

There are lots of ways: