一、CMB2 简介
B2 主题内置了 CMB2 自定义字段库(位于 Library/Cmb2),它可以让你为文章、分类、用户等对象添加字段,并自动生成美观的后台表单。很多 B2 自带的功能(如文章角标、下载设置)都是基于 CMB2 实现的。
二、为文章添加自定义字段
在子主题 functions.php 中添加以下代码,为文章增加一个”自定义提示文字”字段:
Text
<?php
add_action( 'cmb2_admin_init', 'jitheme_post_meta_box' );
function jitheme_post_meta_box() {
$cmb = new_cmb2_box( array(
'id' => 'jitheme_post_meta',
'title' => '自定义字段',
'object_types' => array( 'post' ), // 作用对象:文章
) );
$cmb->add_field( array(
'name' => '提示文字',
'id' => 'jitheme_notice',
'type' => 'textarea_small',
) );
}
三、前台调用字段值
Text
<?php
$notice = get_post_meta( get_the_ID(), 'jitheme_notice', true );
if ( $notice ) {
echo '<div class="post-notice">' . esc_html( $notice ) . '</div>';
}
四、为分类添加字段
Text
<?php
add_action( 'cmb2_admin_init', 'jitheme_term_meta_box' );
function jitheme_term_meta_box() {
$cmb = new_cmb2_box( array(
'id' => 'jitheme_term_meta',
'title' => '分类图标',
'object_types' => array( 'term' ),
'taxonomies' => array( 'category' ),
) );
$cmb->add_field( array(
'name' => '分类图标图片',
'id' => 'b2_tax_img',
'type' => 'file',
) );
}
五、注意事项
1. 字段 ID 请使用唯一前缀(如 jitheme_),避免与 B2 自带字段冲突。
2. 修改字段后,如果前台未生效,请检查模板中是否正确调用 get_post_meta。
3. CMB2 字段类型支持 text、textarea、select、file、colorpicker 等,按需选择。

