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
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).
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.