Skip to content

Instantly share code, notes, and snippets.

@carasmo
Last active June 21, 2022 01:42
Show Gist options
  • Save carasmo/8c7aa4c6d94517fc4c7d to your computer and use it in GitHub Desktop.
Save carasmo/8c7aa4c6d94517fc4c7d to your computer and use it in GitHub Desktop.
example CMB2 repeatable group
/** ====================================================================================
* Functions file
==================================================================================== **/
function yourthemeprefix_yourcpt_metabox_register() {
$prefix = '_cmb_';
$cmb_repeat_test = new_cmb2_box( array(
'id' => $prefix . 'metaboxjff',
'title' => __( 'Repeatable Editor', 'your-text-domain' ),
'object_types' => array( 'page' ), // post type
'show_on' => array( 'key' => 'page-template', 'value' => 'page-test.php' ),
'context' => 'normal',
'priority' => 'high',
'show_names' => true,
) );
// Repeatable group
$group_repeat_test = $cmb_repeat_test->add_field( array(
'id' => $prefix . 'metaboxjff_sections',
'type' => 'group',
'options' => array(
'group_title' => __( 'Editor', 'your-text-domain' ) . ' {#}', // {#} gets replaced by row number
'add_button' => __( 'Add another Editor', 'your-text-domain' ),
'remove_button' => __( 'Remove Editor', 'your-text-domain' ),
'sortable' => true, // beta
),
) );
//* Title
$cmb_repeat_test->add_group_field( $group_repeat_test, array(
'name' => __( 'Test Title', 'your-text-domain' ),
'id' => $prefix . 'test_title_2',
'type' => 'text',
) );
//* Textarea
$cmb_repeat_test->add_group_field( $group_repeat_test, array(
'name' => __( 'Test Content', 'your-text-domain' ),
'id' => $prefix . 'test_content_2',
'type' => 'textarea',
'options' => array( 'textarea_rows' => 8, ),
) );
}
add_action( 'cmb2_init', 'yourthemeprefix_yourcpt_metabox_register' );
/** ====================================================================================
* On the page
==================================================================================== **/
function my_page_function_for_hook() {
$prefix = '_cmb_';
$entries = get_post_meta(get_the_ID() , $prefix . 'metaboxjff_sections', true);
foreach((array)$entries as $key => $entry) {
$title = $content = '';
if ( isset( $entry[ $prefix . 'test_title_2' ] ) )
$title = esc_html( $entry[ $prefix . 'test_title_2' ] );
if ( isset( $entry[ $prefix .'test_content_2' ] ) )
$content = $entry[ $prefix . 'test_content_2' ];
if ( !empty($title) ) {
echo '<h3> ' .$title . '</h3>';
}
if ( !empty($content) ) {
echo $content;
}
} //* end foreach;
} //* end my_page_function_for_hook()
add_action('genesis_after_entry', 'my_page_function_for_hook');
@kaziramjan
Copy link

how to use image ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment