keepcalculator

06 Numbers and Powers

How to Create Custom Meta Boxes with CMB2 in WordPress

Card No. 06·68509 · Updated · Standard formula, shown below

This guide walks you through creating custom meta boxes in WordPress using the CMB2 library. You’ll learn how to add fields like text inputs, checkboxes, and image uploads to your post edit screens, and how to save and retrieve that data. No prior experience with CMB2 is needed, but basic knowledge of PHP and WordPress theme/plugin development is helpful.

What You’ll Need

  • A WordPress site (self-hosted or local) with admin access.
  • A code editor (e.g., VS Code, Sublime Text).
  • FTP or file manager access to your WordPress installation.
  • Basic understanding of PHP and how WordPress hooks work.
  • CMB2 library (either as a plugin or included in your theme/plugin).

Step-by-Step

  1. Install CMB2. The easiest way is to install the CMB2 plugin from the WordPress repository. Alternatively, you can download the library from GitHub and include it in your theme or plugin. For this guide, we’ll assume you’re using the plugin.
  2. Create a custom plugin or add to your theme’s functions.php. It’s cleaner to create a small plugin. Create a folder in wp-content/plugins/ named my-meta-boxes and inside it create a file my-meta-boxes.php with the plugin header.
  3. Include the CMB2 library (if not using the plugin). If you’re not using the plugin, you need to require the CMB2 file. Add this to your plugin file:
    require_once 'cmb2/init.php';
    Make sure the path is correct.
  4. Create a function to define your meta boxes. This function will return an array of field definitions. Start with a basic example:
  5. Add the function code. Here’s a simple example that creates a text field and a checkbox on the post edit screen:
    function my_metaboxes() {
        $prefix = '_my_'; // prefix for field IDs
    
        $cmb = new_cmb2_box( array(
            'id'           => $prefix . 'metabox',
            'title'        => 'My Custom Fields',
            'object_types' => array( 'post' ), // post type
            'context'      => 'normal',
            'priority'     => 'high',
        ) );
    
        $cmb->add_field( array(
            'name' => 'Subtitle',
            'id'   => $prefix . 'subtitle',
            'type' => 'text',
        ) );
    
        $cmb->add_field( array(
            'name' => 'Featured?',
            'id'   => $prefix . 'featured',
            'type' => 'checkbox',
        ) );
    }
    add_action( 'cmb2_admin_init', 'my_metaboxes' );
        
  6. Add more field types. CMB2 supports many field types: text, textarea, select, radio, image, file, date, colorpicker, and more. For a select dropdown, you’d add:
    $cmb->add_field( array( 'name' => 'Priority', 'id' => $prefix . 'priority', 'type' => 'select', 'options' => array( 'low' => 'Low', 'high' => 'High' ) ) );
  7. Save the file and reload your post editor. You should see your new meta box with the fields.
  8. Retrieve the values in your theme templates. Use get_post_meta() to get the values. For example:
    $subtitle = get_post_meta( get_the_ID(), '_my_subtitle', true );
  9. Display the values. In your template file (e.g., single.php), echo the value where you want it to appear.

Common Mistakes

  • Not using a unique prefix. Field IDs must be unique. Use a prefix like _my_ to avoid conflicts.
  • Forgetting to include CMB2. If you’re not using the plugin, you must require the library file, or nothing will show.
  • Using the wrong hook. The correct hook is cmb2_admin_init, not admin_init.
  • Not checking if CMB2 is loaded. If you’re using the plugin, it’s fine, but if you’re embedding the library, ensure it’s loaded before your code runs.
  • Calling new_cmb2_box() outside a function. Always wrap your code in a function hooked to cmb2_admin_init.

Tips

  • Use repeatable groups for complex data like multiple team members or gallery images.
  • Add field validation using the sanitization_cb parameter to keep data clean.
  • Use the cmb2_metabox_form shortcode to display forms on the front end if needed.
  • Keep your code organized in a separate plugin file to make it reusable across themes.

Troubleshooting

  • Meta box not showing: Check that CMB2 is active (if plugin) or correctly included. Also verify the object_types array includes the post type you’re editing.
  • Fields not saving: Ensure your field IDs have a prefix and that you’re using the correct hook. Also check for PHP errors in the console.
  • Values not displaying: Make sure you’re using the correct meta key (with prefix) and that you’re calling get_post_meta() inside the loop or with a valid post ID.
  • Conflicts with other plugins: If CMB2 is already included by another plugin, you may get a notice. Use the plugin version to avoid duplicates.

Frequently Asked Questions

Can I use CMB2 with custom post types?

Yes, simply add the custom post type slug to the object_types array.

How do I add an image upload field?

Use the file or image field type. The file type allows any file, while image restricts to images. Add 'type' => 'file' and set 'options' => array( 'url' => false ) to store the attachment ID.

Can I show the meta box on the front end?

Yes, CMB2 has a shortcode [cmb2_metabox_form] that can display a form on the front end. You can also manually render fields using cmb2_get_metabox().

How do I create a repeatable group?

Use the group field type. Define sub-fields inside the group, and CMB2 will handle the repeatable interface.

Is CMB2 compatible with Gutenberg?

Yes, CMB2 works with Gutenberg. Meta boxes appear in the editor as a separate panel below the content area.

Can I use CMB2 in a theme?

Yes, you can include the library in your theme and define meta boxes in functions.php. Just ensure you include the library before using it.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →