views:

33

answers:

2

Hello all,

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.

I understand that I'll need some javascript to add this facility (and something I don't mind writing) but what I'm struggling with in my poor, useless brain is how to save these to the database. I want to achieve this using WordPress meta so that I don't add any unnecessary database tables and I'm sure it's possible I just can't quite fathom the principles of how to save the data.

Pointers to any tutorials would be brilliant, or some examples of plugins which already do this kind of thing would be very gratefully received.

A: 

Hi Richard, 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 bedroom[width], bedroom[num_windows], bedroom[bed_type] etc, you would store an array within the post_meta table, so when you get the post meta for the bedroom of a house, it would return an array of arrays (the first level represnting the rooms, the second representing the attributes of a room

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

Damian Jakusz-Gostomski
Nice, thanks Damian. The phrase 'an array of arrays' scares the living crap out of me (I'm much more a designer than developer) but I think I see where you're going with it. I wonder if there's any example code with this sort of functionality already done. Ponder ponder. Thanks very much, Sir Scrabble surname. (Just for the record I 'know' Damian and I'm not being an arsehole ;) )
iamfriendly
A: 
cnix