Advanced dynamic WordPress custom meta boxes
I’m in the process of creating a plugin which creates several custom post types (CPT) (all of which work just fine). Some of these CPTs require a ‘custom write panel’ which basically means that it has a set of custom meta boxes rather than the bog-standard ‘edit’ box you get with your posts or pages.
One of these CPTs requires a ‘dynamic’ set of meta boxes which basically has an indeterminate amount of values. I’ll try and give an example:
(this isn’t what I’m doing, but it seems like a decent example of how I’d like it to work)
Imagine we have a CPT of ‘houses’ and one of the custom meta options for this CPT is ‘bedrooms’ – obviously, different houses have different amount of bedrooms, all of which have different properties. So, I’d like to be able to allow the user to add several different properties about a bedroom i.e.
Dimensions, aspect, number of windows and floor type
When the user has added these details for the first bedroom, if the house has a second bedroom then I would like them to have an ‘add bedroom’ button and another set of these meta boxes is added so they can fill out the details about bedroom 2.
Pointers to any tutorials would be brilliant, or some examples of plugins which already do this kind of thing would be very gratefully received.
I think the best way to do this would be to use arrays within the forms. If you just had a collection of values which were saved to post_meta, you would only be able to link them back to the post (in this case house) but not which dimensions match which floor type etc
If you had the names of each form field something like
You could even take it a step further if you wanted, and name the field bedrooms[i][attribute] where i is a counter you maintain within the JS. Then you would only have a single piece of post meta for all the bedrooms