
🛠 Come aggiungere meta box in WordPress con CMB2: una guida completa
Standard WordPress fields are enough until your first custom project. The moment you need to display product specs on a card, add a gallery to a page, or attach a shipping terms block, you hit the editor's limitations: title, text, categories, that's it.
There is a way out, and it's not ACF Pro at $149 per year. Custom meta boxes add arbitrary fields directly to the post editing interface without a visual builder and without a dozen unnecessary modules. CMB2 does exactly that: it provides a PHP API for describing meta boxes in code that lives in version control, not in the database.
Below is the complete workflow: from installing the plugin to displaying data on the frontend. By the end of this article, you will have a working meta box file that adapts to any content type from pages to WooCommerce products.
💡 Quick overview:
- Install CMB2 from the WordPress.org directory: the plugin is free and installs in two clicks.
- Create a
metaboxes.phpfile in your theme folder and describe the required fields via thecmb2_admin_inithook. - Include the file in
functions.phpwith a singlerequire_onceline and verify the meta box in the admin panel. - Display saved data on the frontend via
get_post_meta()with proper escaping.
What is CMB2: code instead of a visual builder
CMB2 is a developer library that creates meta boxes, custom fields, and forms in WordPress. Out of the box, it supports dozens of field types: text, WYSIWYG editor, file upload, date picker, color picker, radio buttons, dropdowns, repeaters, and groups.
The main difference from ACF: CMB2 has no visual builder. All meta boxes are described in PHP files within your theme. For developers, this is a plus: configuration lives in Git, it cannot be accidentally deleted through the admin panel, and migration between staging and production comes down to code deployment. At the same time, CMB2 is completely free, while ACF Pro will cost you around $149 per year for repeatable fields and groups.
The library has been actively maintained since 2014. On WordPress.org, the plugin has a 5-star rating and over 300,000 active installations. The GitHub repository receives regular updates: the latest release addressed compatibility with PHP 8.4 and WordPress 6.7. This is not an abandoned project that will be dropped in six months.
Step 1: Install the plugin
Go to Plugins → Add New, type "CMB2" in the search box, and click "Install." After activation, the plugin loads its engine but does not change anything in the admin panel by itself: meta boxes will appear only after you describe them in code.

If you are including CMB2 manually inside your theme without installing it through the admin panel, add the following to the beginning of functions.php:
1 require_once __DIR__ . '/cmb2/init.php';
Two important points. First: init.php should load as early as possible, outside of any hooks. Do not wrap it in if ( ! class_exists(... checks; CMB2 handles duplicate loading conflicts on its own. Second: with manual inclusion, you will need to update CMB2 manually, unlike auto-updates through the admin panel.
Step 2: Write the meta box file
Create a cmb2-metaboxes folder in the root of your child theme and a metaboxes.php file inside it. This file will contain all your field definitions.
Below is working code that adds a text editor, a short description, and a badge selector to WooCommerce products. Copy it into metaboxes.php:
1 add_action( 'cmb2_admin_init', 'sdstudio_register_metaboxes' ); 2 3 function sdstudio_register_metaboxes() { 4 5 $prefix = '_sdstudio_'; 6 7 $cmb = new_cmb2_box( array( 8 'id' => 'product_extra_info', 9 'title' => __( 'Дополнительная информация о товаре', 'cmb2' ), 10 'object_types' => array( 'product' ), 11 'context' => 'normal', 12 'priority' => 'high', 13 'show_names' => true, 14 ) ); 15 16 $cmb->add_field( array( 17 'name' => __( 'Описание для карусели на главной', 'cmb2' ), 18 'desc' => __( 'Текст, который будет показан в слайдере товаров.', 'cmb2' ), 19 'id' => $prefix . 'carousel_desc', 20 'type' => 'wysiwyg', 21 'options' => array( 22 'textarea_rows' => 5, 23 ), 24 ) ); 25 26 $cmb->add_field( array( 27 'name' => __( 'Короткое описание', 'cmb2' ), 28 'desc' => __( 'Одна строка — для карточки товара в сетке.', 'cmb2' ), 29 'id' => $prefix . 'short_desc', 30 'type' => 'textarea_small', 31 ) ); 32 33 $cmb->add_field( array( 34 'name' => __( 'Бейдж товара', 'cmb2' ), 35 'desc' => __( 'Метка «Новинка», «Хит» или «Распродажа».', 'cmb2' ), 36 'id' => $prefix . 'badge', 37 'type' => 'select', 38 'show_option_none' => true, 39 'options' => array( 40 'new' => __( 'Новинка', 'cmb2' ), 41 'hit' => __( 'Хит', 'cmb2' ), 42 'sale' => __( 'Распродажа', 'cmb2' ), 43 ), 44 ) ); 45 46 }
What's happening here: the cmb2_admin_init hook fires when the admin panel loads and registers the meta box on the product editing page. new_cmb2_box() creates a container with the title "Additional product information," and three add_field() calls add fields to it: a WYSIWYG editor, a compact text field, and a dropdown with preset options. Each field gets a unique id with the _sdstudio_ prefix to avoid conflicts with other plugins.

If you need regular pages instead of WooCommerce, replace 'object_types' => array( 'product' ) with 'object_types' => array( 'page' ). For multiple content types, list them: array( 'page', 'post' ).
For the full list of field types, see the official CMB2 documentation on GitHub. Dozens of options are available out of the box: from plain text and WYSIWYG editors to file uploads, color pickers, radio buttons, and taxonomies. Choose the right type for your specific task based on documentation, not guesswork.
Step 3: Include it in functions.php
Now you need to load the file you created. Open functions.php in your child theme and add a single line before the closing ?> tag, or at the end of the file if there is no closing tag:
1 require_once __DIR__ . '/cmb2-metaboxes/metaboxes.php';
Before adding the code, back up functions.php. A syntax error in require_once will crash the site with a fatal PHP error, and you will only be able to restore the file via FTP or your hosting panel. After saving, open any product in the admin panel and verify that the "Additional product information" meta box appears below the content editor.
Fill in the test fields and click "Update." CMB2 automatically saves the data to the wp_postmeta table. No additional save_post hook calls are required: the library intercepts the post save and processes its fields on its own.
Step 4: Display data on the frontend
The data is saved in the database; now you need to show it to visitors. Open the theme file responsible for the product page, usually single-product.php or content-single-product.php. Add the code inside the WordPress loop:
1 <?php 2 $carousel_desc = get_post_meta( get_the_ID(), '_sdstudio_carousel_desc', true ); 3 $badge = get_post_meta( get_the_ID(), '_sdstudio_badge', true ); 4 5 if ( ! empty( $carousel_desc ) ) : ?> 6 <div class="product-carousel-desc"> 7 <?php echo wp_kses_post( $carousel_desc ); ?> 8 </div> 9 <?php endif; ?> 10 11 <?php if ( ! empty( $badge ) ) : ?> 12 <span class="product-badge product-badge--<?php echo esc_attr( $badge ); ?>"> 13 <?php echo esc_html( $badge ); ?> 14 </span> 15 <?php endif; ?> 16
Breakdown: get_post_meta() retrieves the value by field ID. For a WYSIWYG field, use wp_kses_post(), which allows permitted HTML tags and filters potentially dangerous ones. For plain text or a select, esc_html() is sufficient: it converts special characters to HTML entities and prevents XSS.
If the meta box is created for pages ('object_types' => array( 'page' )), place this same code in page.php or content-page.php. The mechanics are the same: get_post_meta() inside the loop, escaping based on field type.
Video: CMB2 from installation to a working meta box
In this 20-minute tutorial, the author walks through the complete workflow: installation, field creation, file inclusion, and frontend data display. Useful to watch if the text instructions left gaps.
⁉️🤔 Frequently asked questions
How is CMB2 different from ACF?
ACF provides a visual field builder right in the admin panel: you can assemble a meta box without writing a single line of code. CMB2 requires describing fields in PHP files within your theme. For developers who store configuration in Git, CMB2 is more convenient: meta boxes do not depend on the database state, they cannot be accidentally deleted through the admin panel, and migration between staging and production comes down to code deployment. ACF Pro costs from $149 per year for repeatable fields and groups; CMB2 is free.
Can CMB2 be used without installing the plugin?
Yes. Copy the CMB2 folder inside your theme and include
init.phpinfunctions.php, as shown in step 1. This approach is convenient for premium themes that should work immediately after activation without requiring the user to install a third-party plugin. The downside: you will need to update CMB2 manually with each new version.
Do CMB2 fields work in the Gutenberg editor?
Yes, CMB2 meta boxes are displayed below the Gutenberg editor in the familiar way, in the section below the content. However, out of the box, they do not integrate into editor blocks. If you need to embed a field directly into a block, additional development via the CMB2 API and
register_block_type()will be required.
What should I do if the meta box does not appear in the admin panel?
Check three things. First: does
object_typesmatch the type of post being edited? For WooCommerce products, you need'product', not'post'. Second: is there a PHP syntax error? EnableWP_DEBUGinwp-config.phpand check the log. Third: is the fieldidprefix conflicting with another plugin? Use a unique prefix like_sdstudio_.
Can I create repeatable field groups?
Yes. CMB2 supports repeatable fields via the
'repeatable' => trueflag and repeatable groups via$cmb->add_group_field(). A group allows you to add a "Characteristic: value" block and create new instances with an "Add row" button directly in the admin panel.
Does CMB2 work with multisite?
Yes, the plugin is fully compatible with WordPress Multisite. Meta boxes can be registered globally in the
functions.phpof the active network theme or individually for each site. Theget_post_meta()call works the same in both modes.
CMB2 or ACF: which approach to choose for your task
CMB2 solves exactly one task: creating custom meta boxes through code, with configuration stored in theme files rather than the database. The choice comes down to your workflow, not an abstract "which is better."
If you are a developer and store all project configuration in Git, go with CMB2. Meta boxes live in
metaboxes.php, deploy with your theme, and do not require database synchronization between staging and production.If you need a visual builder, repeatable flexible fields, and ready-made Gutenberg blocks without writing code, go with ACF Pro. The subscription starting at $149 annually pays off in prototyping speed.
If your project already uses CMB2 and the meta boxes work reliably, stay with it. The library is not abandoned, does not require urgent migration, and regularly receives compatibility updates.
Try both approaches on a test site: build the same meta box in CMB2 and in ACF. The difference in approach will become obvious in 20 minutes. Which tool do you use? Share in the comments.



