The CMB2 Repeater group is easy to set up, populate and render. And it is fast and only uses one post meta database row.
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
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.
The page included the “This is a little demo…” text and the unordered list was appended to it. Simple.