Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

CMB2 is a developer toolkit for adding custom fields and metaboxes to WordPress. You define a box with new_cmb2_box(), add controls with $cmb->add_field(), and read saved values through WordPress metadata functions such as get_post_meta(). The same API can attach data to posts, custom post types, users, taxonomy terms, comments, and option pages.

This guide shows both supported installation models, a complete working metabox, placement rules, repeatable data, custom field types, retrieval and escaping, and the failures that most often make a box disappear or return an empty value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What CMB2 does

CMB2 supplies the registration, rendering, sanitization, and storage plumbing for WordPress metaboxes and custom fields. It is not a visual page builder. You still write PHP that describes the data your content model needs, then WordPress stores the submitted values as metadata.

The project description calls CMB2 “a developer’s toolkit for building metaboxes, custom fields, and forms for WordPress that will blow your mind.” In practical terms, it gives you:

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.
  • Metabox registration for standard posts and custom post types.
  • Fields on users, taxonomy terms, comments, and custom option pages.
  • Built-in controls for common input types.
  • Repeatable fields and repeatable groups for structured lists.
  • Hooks for rendering and sanitizing field types that are not built in.
  • Stable metadata keys based on the field IDs you choose.

Use CMB2 when a theme or plugin needs a defined content schema that editors can fill in on an admin screen. A book plugin, for example, might store a subtitle and ISBN beside the normal post title and editor. A custom post type can use the same approach for dimensions, specifications, event dates, or editorial flags.

Requirements and installation choices

The repository currently lists PHP 7.4 as CMB2’s minimum PHP requirement and a stable tag of 2.13.4. Those are project version metadata, not a performance or adoption measurement; verify compatibility with the PHP and WordPress versions your site actually runs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can install CMB2 as a WordPress.org plugin or bundle the library inside your own theme or plugin. Choose one method only. Loading a plugin copy and a bundled copy together can create duplicate classes and unpredictable initialization.

Method What you do Maintenance implication
WordPress.org plugin Install CMB2 from the WordPress admin or upload the plugin, then activate it. The plugin supplies its own bootstrap and can be updated through the normal plugin workflow.
Bundled library Place the CMB2 directory in your theme or plugin and require cmb2/init.php early. Keep the CMB2 directory unedited so you can replace it with a newer release. Your integration code belongs outside that directory.

Install the plugin

  1. In WordPress, open Plugins and choose Add New.
  2. Search for CMB2, install the WordPress.org plugin, and activate it.
  3. Put your registration code in the plugin that owns the fields, or in the active theme if the fields are theme-specific.
  4. Do not add a second bundled copy unless you deactivate and remove the plugin copy.

Bundle CMB2 in a plugin or theme

Copy the CMB2 directory into your project and leave its files unchanged. Require its bootstrap outside a hook, before you register any boxes:

<?php
require_once __DIR__ . '/cmb2/init.php';

The path is case-sensitive on many hosting systems. A directory named CMB2 is not interchangeable with cmb2 on a case-sensitive server. The bootstrap must load early enough for the cmb2_admin_init action and CMB2 classes to be available.

Register a basic post metabox

The normal registration sequence has three parts: hook your callback to cmb2_admin_init, create a box with new_cmb2_box(), and add controls with $cmb->add_field(). This complete example creates two text fields on the standard post edit screen:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
// Needed only when CMB2 is bundled rather than installed as a plugin.
require_once __DIR__ . '/cmb2/init.php';

add_action( 'cmb2_admin_init', 'acme_register_book_metabox' );
function acme_register_book_metabox() {
    $cmb = new_cmb2_box( array(
        'id'           => 'acme_book_details',
        'title'        => __( 'Book details', 'acme' ),
        'object_types' => array( 'post' ),
        'context'      => 'normal',
        'priority'     => 'high',
        'show_names'   => true,
    ) );

    $cmb->add_field( array(
        'name' => __( 'Subtitle', 'acme' ),
        'id'   => 'acme_subtitle',
        'type' => 'text',
    ) );

    $cmb->add_field( array(
        'name' => __( 'ISBN', 'acme' ),
        'id'   => 'acme_isbn',
        'type' => 'text',
    ) );
}

With the plugin active and the code loaded, edit a post. A Book details box should appear in the normal content area. CMB2 uses each field’s id as the metadata key, so the values are saved under acme_subtitle and acme_isbn.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Why the IDs matter

Use a unique prefix for both the box ID and every field ID. Generic names such as details or subtitle can collide with another plugin or an older implementation. IDs become persistent database keys; changing one later makes existing values appear to have disappeared because your code is now reading a different key.

Keep IDs stable once content has been entered. If you must rename one, plan a metadata migration that copies the old key to the new key before switching the display code.

Attach the box to the right screen and position it

The object_types argument determines which WordPress object receives the box. For the built-in post editor, use array( 'post' ). For a custom post type, replace post with that post type’s registered slug:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
'object_types' => array( 'acme_book' ),

The slug must match the value passed to register_post_type(), not the post type’s display name. If the slug is wrong, the callback can run successfully while no box appears on the screen.

Box placement is controlled by several arguments:

Argument Common values Effect
context normal, side, advanced Chooses the main column, sidebar, or lower advanced area.
priority high, default, low Influences vertical order among boxes in the same context.
show_names true or false Controls whether CMB2 displays field labels beside controls.
Alternate position after_title or after_editor in the supported box configuration Places the box around the title or editor instead of the normal metabox regions.

A normally placed metabox needs a title. WordPress will not display a standard box without one unless you deliberately use an alternate no-wrap configuration. Give every normal box a meaningful, translatable title so editors can identify it.

Choose field types for your data

CMB2 includes field types for common controls, including text inputs and other standard values documented by the project. The maintained example-functions.php file is worth checking when selecting a type because documentation can lag behind the implementation.

Keep the field type aligned with the value you intend to store. A short identifier, ISBN, or label can use text; a longer editorial note needs a textarea-style control; a choice among known values should use a select, radio, or checkbox control where appropriate. The exact arguments vary by type, so copy the current example for that control rather than relying on an outdated snippet.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Every field definition normally includes:

  • name: the human-readable label shown to editors.
  • id: the persistent metadata key.
  • type: the CMB2 control to render.
  • Optional descriptions, defaults, display conditions, and type-specific settings from the current field guide.

Use translation functions for labels and descriptions, and prefix your text domain consistently with the rest of your plugin or theme.

Build repeatable fields and groups

Repeatable fields let an editor add multiple values without knowing how many rows will be needed. Repeatable groups combine several fields into one repeatable record, such as an author name, role, and profile URL that must stay together.

The project readme states that most field types can be repeatable and that repeatable groups are supported, but it also warns that not every control behaves well inside a group. Test the specific type you choose, especially controls that depend on media frames, complex JavaScript, or serialized values.

A repeatable field is declared by adding the repeatable setting supported by that field type. A repeatable group uses a group definition containing child fields. Because the exact argument names and supported combinations can change with the installed CMB2 version, start from the version’s current example-functions.php and adapt the IDs and labels rather than mixing examples from unrelated releases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When you read a repeatable value, expect an array rather than a scalar. Inspect the returned structure before formatting it:

$authors = get_post_meta( get_the_ID(), 'acme_authors', true );
if ( is_array( $authors ) ) {
    foreach ( $authors as $author ) {
        $name = isset( $author['name'] ) ? $author['name'] : '';
        echo esc_html( $name );
    }
}

Do not assume every child key exists. Editors may leave optional controls blank, and older rows may have been saved before a new child field was introduced.

Retrieve saved CMB2 values

For a post or custom post type, use the field ID as the metadata key and call WordPress’s metadata API:

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.
<?php
$subtitle = get_post_meta( get_the_ID(), 'acme_subtitle', true );
echo esc_html( $subtitle );

The third argument, true, asks for one value. Without it, WordPress returns an array of all values stored under that key. CMB2 may store structured or repeatable data as arrays, so select the return shape that matches your field.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Escape at output time

Storage and retrieval are separate from presentation safety. Escape the value for the context in which you print it: esc_html() for visible text, esc_attr() for an HTML attribute, and the appropriate URL or markup escaping function when output is a link or trusted formatted content. Do not run every value through one escaping function regardless of context.

For a value used in a template, retrieve it close to where it is rendered and handle an empty value intentionally:

$isbn = get_post_meta( get_the_ID(), 'acme_isbn', true );
if ( $isbn !== '' ) {
    echo '<p class="book-isbn">' . esc_html( $isbn ) . '</p>';
}

When debugging, inspect the raw value before applying formatting or escaping. That distinguishes an empty database value from a display bug.

Use CMB2 with users, terms, comments, and option pages

CMB2 is not limited to post edit screens. Its supported object contexts include users, taxonomy terms, comments, and custom option pages. The registration pattern remains the same, but the object type and retrieval API change with the object being edited.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Users: register the box for the user context and retrieve the field with a user-meta function using the user ID.
  • Taxonomy terms: register against the term context and read the value with a term-meta function using the term ID.
  • Comments: register against the comment context and read comment metadata with the comment ID.
  • Option pages: register an options page and read the resulting option value through the option storage mechanism defined by that page.

The field IDs remain the names you control, but the storage API is not interchangeable: do not call get_post_meta() for a user or term field.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Create a custom field type

If CMB2’s built-in controls do not represent your data, define a custom type with two hooks:

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
  • cmb2_render_{field-type} renders the control in the editor.
  • cmb2_sanitize_{field-type} validates and transforms submitted data before it is stored.

Replace {field-type} with the type string used in your field definition. For example, a type named text_email uses these hook names:

add_action( 'cmb2_render_text_email', 'acme_render_text_email', 10, 5 );
function acme_render_text_email( $field, $escaped_value, $object_id, $object_type, $field_type ) {
    printf(
        '<input type="email" class="regular-text" name="%s" value="%s" />',
        esc_attr( $field_type->_name() ),
        esc_attr( $escaped_value )
    );
}

add_filter( 'cmb2_sanitize_text_email', 'acme_sanitize_text_email', 10, 4 );
function acme_sanitize_text_email( $null, $new_value, $object_id, $field_args ) {
    return sanitize_email( $new_value );
}

The exact callback arguments should follow the current custom-field guide for your CMB2 version. Rendering must output a control that uses CMB2’s supplied field name, and sanitization must reject or normalize invalid input rather than trusting the browser’s HTML type attribute. A browser can submit arbitrary values, so server-side sanitization is essential.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical registration workflow

  1. Choose ownership. Put registration in a plugin when the data should survive a theme change. Put it in a theme only when the fields are inseparable from that theme’s templates.
  2. Load CMB2 once. Use the activated plugin or require the bundled cmb2/init.php outside a hook.
  3. Pick stable, prefixed IDs. Treat box and field IDs as database schema names.
  4. Register on cmb2_admin_init. Create the box and add fields inside the callback.
  5. Target the exact object slug. Confirm the custom post type or other object context matches the screen being edited.
  6. Set placement deliberately. Supply a title and choose context and priority; use an alternate position only when the editor experience requires it.
  7. Save a test value. Edit the target object, enter a distinctive value, and update it.
  8. Read the exact key. Call the metadata function with the same field ID and inspect the raw result.
  9. Escape for output. Apply context-appropriate escaping in the front end or admin display.

Troubleshoot a missing box or empty value

The metabox does not appear

  • Confirm CMB2 is activated or that the bundled bootstrap is being required.
  • Check that the bundled path is exactly cmb2/init.php, including letter case.
  • Verify the registration callback is attached to cmb2_admin_init.
  • Compare object_types with the screen’s actual post-type slug or object context.
  • Make sure a normally positioned box has a non-empty title.
  • Check the screen’s “Screen Options” panel; an editor can hide a metabox without changing your PHP.

The box appears but values do not save

  • Use unique IDs and confirm the field ID has not changed between renders.
  • Check that the field type is supported in the installed CMB2 version and that its arguments match the current examples.
  • Update the object after entering a value, then inspect the database value through the appropriate metadata API.
  • For repeatable groups, verify that your code handles arrays and optional child keys.
  • Ensure you are not loading two copies of CMB2, which can cause class or hook conflicts.

The value exists but output is wrong

  • Inspect the raw return value before formatting it.
  • Use true as the third argument of get_post_meta() when you need one scalar value.
  • Use the metadata API that matches the object type.
  • Escape for the final HTML context instead of applying an unrelated sanitizer.

Maintenance decisions that prevent future problems

Keep CMB2 itself unmodified when bundled. Put custom field callbacks, templates, and migration code in your own plugin or theme so an update can replace the library safely.

Document each field ID and the object it belongs to. Metadata keys are long-lived contracts between the editor, saved content, and templates. If a field is removed, decide whether to leave historical metadata in place, migrate it, or delete it deliberately; do not silently reuse the old ID for an unrelated meaning.

Review the current field examples when upgrading CMB2. The official field-types documentation notes that written documentation can lag the implementation, while the shipped examples reflect the code in the release you installed.

Finally, keep the data model narrow. A few explicit fields are easier to validate, query, and migrate than a single opaque blob. Use a repeatable group when records have a consistent shape, and a custom field type only when an existing control cannot express the required value.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Summary

A reliable CMB2 metabox follows a predictable pattern: load CMB2 once, register on cmb2_admin_init, create a titled box with the correct object_types, add fields with stable prefixed IDs, and retrieve those IDs through the metadata API for the relevant object. Repeatable structures extend the same model, while custom types use cmb2_render_... and cmb2_sanitize_... hooks. Most failures come from loading the library incorrectly, targeting the wrong object slug, omitting a title, changing a metadata key, or reading a structured value as though it were a scalar.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.