The CMB2 Repeater group is easy to set up, populate and render. And it is fast and only uses one post meta database row.
Over the last two months I have experimented with changing from ACF Pro to CMB2. I was inspired by a Bill Erickson post where he mentioned that he prefers CMB2 over ACF for most circumstances.
Next up is to experiment with the repeater functionality of CMB2 that is available via the ‘group’ field type. The ‘group’ is not a true field type but rather a ‘container’ that also supports adding other fields as a repeatable group. It also serialises the field data of the group into a single post_meta entry!
I had a short discussion about CMB2 with Heidi Jermyn and she mentioned that repeater blocks weren’t available when she had used CMB2. I had used the ‘group‘ field type for a logical grouping of fields but not repeater fields, so I decided to try it out.
Make a list
The field setup is quite simple. In my previous use of the ‘group’ field type it was only for layout purposes so the ‘repeatable‘ option was set to ‘false.’ This time ‘repeatable‘ is ‘true‘.
The repeating fields are just two text fields – one for a blog post title and the other for its url. This is a contrived demo so I kept things simple. I also show the CMB2 meta box on all pages (object_types => array( ‘page’ )) for simplicity.
Field Setup Code
Edit Page view
I set the text for ‘add_button‘ (to ‘Add Another Post‘) and ‘remove_button‘ (to ‘Remove Post‘) to make it clear how to add and remove repeater items.
Aside: the order of repeated items cannot be changed (this is unrelated to my code).
Edit: As Justin pointed out in the comments, repeated items can be resorted, by setting 'sortable'=>true
to the ‘options‘ block. This adds two arrow buttons at the bottom of each block (as shown in the updated image above) so that you can move the block up or down one.
Display the data
Displaying the data isn’t difficult. I append it to ‘the_content‘, again for simplicity.
To avoid any PHP warning, I check that the ‘blog_group‘ post_meta field exists and then use the ‘url‘ and ‘title‘ IDs to retrieve the repeater data and create an unordered list.
End Result
The page included the “This is a little demo…” text and the unordered list was appended to it. Simple.
Great little demo! In response to your aside, “the order of repeated items cannot be changed”, this can be toggled on with the `sortable` option: https://github.com/CMB2/CMB2/blob/trunk/example-functions.php#L492
@Justin – Thanks! I’ll give it a try and update the post.
@Justin – ‘sortable’ => true is brilliant. I have uploaded a new screenshot in the Edit Page view section and updated the code and notes. Thanks again.