Use a custom 'show_on_cb' function to only show the CMB2 metabox when editing the front page.
I am a big fan of CMB2 for metaboxes and custom fields. I prefer it over Advanced Custom Fields because it doesn’t slow down the front end and because site admins cannot edit the fields (and break things)
I frequently refer to the CMB2 wiki, especially the Field Types section. On one project I needed to show the metabox only on the home page (which was set to a static page). I could have created an options page but I wanted to learn about custom filters to control where the metabox displayed and because I felt it was a better user experience to be able to change settings while editing the home page.
Custom show_on_cb filter
The CMB2 wiki has an extensive list of examples of custom ‘show_on_cb‘ filters.
Most of my uses of CMB2 has used the ‘object_types‘ field to set the post type (post, page, options-page) where the metabox will be displayed. This can be enhanced by using the ‘show_on_cb‘ field.
The wiki has an example that filtered the ‘show_on‘ parameter but I felt that it was a bit complicated. I like to keep things simple so I chose to use the ‘show_on_cb‘ (callback) field. This ensures that the callback function is only called for this metabox, not any other CMB2 metabox that the site may use.
The page ID is passed to the callback function in the $cmb object ($cmb->object_id member variable). This makes for a very simple callback. A lot less code than the wiki example!
The callback function is very simple. I could have put it on one line.
The full code shows where the callback function is specified in the new_cmb2_box() call.
As an aside, the code also show how the validate that a text field only has numbers (using the \d* regular expression pattern).