reaktivstudios / cmb2-flexible-content
为 CMB2 的灵活内容字段。
dev-master
2018-11-09 21:44 UTC
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-24 23:17:36 UTC
README
CMB2 灵活字段允许创建分组布局,用户可以选择并切换这些布局。每个布局组包含一组现有的 CMB2 字段,这些字段在字段设置中以数组形式定义。这些布局组可以切换、排序和重复。
数据本身被保存到字段 ID 中,以序列化和可迭代的数组形式,并附加布局组 ID。
添加灵活字段
添加灵活字段与添加其他任何 CMB2 字段相同。唯一的添加是 layouts
选项,它应该包含一个数组的数组,每个数组包含一个单独的组。
首先,设置标准的 CMB2 元盒
// Basic CMB2 Metabox declaration
$cmb = new_cmb2_box( array(
'id' => 'prefix-metabox-id',
'title' => __( 'Flexible Content Test' ),
'object_types' => array( 'post', ),
) );
Then add your flexible field definition. Each layout group should be defined in the layouts array, with the `ID` for that group as its key. Each layout group can contain a `title` and a list of CMB2 `fields`.
// Sample Flexible Field
$cmb->add_field( array(
'name' => __( 'Test Flexible', 'cmb2-flexible' ),
'desc' => __( 'field description (optional)', 'cmb2-flexible' ),
'id' => 'prefix_flexible',
'type' => 'flexible',
'layouts' => array(
'text' => array(
'title' => 'Text Group',
'fields' => array(
array(
'type' => 'text',
'name' => 'Title for Text Group',
'id' => 'title',
),
array(
'type' => 'textarea',
'name' => 'Description for Text Group',
'id' => 'description',
)
),
),
'image' => array(
'title' => 'Image Group',
'fields' => array(
array(
'type' => 'file',
'name' => 'Image for Image Group',
'id' => 'title',
),
array(
'type' => 'textarea',
'name' => 'Description for Image Group',
'id' => 'description',
)
),
),
)
) );
从灵活字段获取数据
灵活字段存储在单个元键中,可以使用 WordPress API 获取。这将返回一个数据数组,每个数据都有定义为 layout
的布局键和按字段 ID 保存的组数据。
$flexible_fields = get_post_meta( $post_id, 'flexible_field_name', true );
foreach( $flexible_fields as $field ) {
if ( 'text' === $field['layout'] ) { ?>
<h2><?php echo esc_html( $field['title'] ); ?></h2>
<?php echo esc_html( $field['description'] );
}
}