0

I am creating a plugin, where the user can create forms with an unlimited amount of fields. I would like to store each field the user creates as an array in a post meta field. What would the code look like for this please? (This is the first plugin i've ever created). @Wyck previously touched on this topic below, but didn't outline the complete code. I'm quite confused about the requirements.

Link to this topic discussed previously

Thanks!

5
  • Please, post the code you are using and specify what doesn't work.
    – brasofilo
    Mar 7, 2013 at 21:54
  • I think there was a typo in the example should be <?php add_post_meta(7, 'fruit', [ 'banana', 'apple', 'tornado', 'bob saget' ] ); ?>
    – user27457
    Mar 7, 2013 at 21:56
  • @Magenta Cuda Thanks, but it is saying unexpected '['
    – user28566
    Mar 7, 2013 at 22:01
  • @brasofilo I was using the code magenta cuda corrected, from the link, but still have an issue with it. Unexpected '[' .
    – user28566
    Mar 7, 2013 at 22:03
  • <?php add_post_meta(7, 'fruit', array( 'banana', 'apple', 'tornado', 'bob saget' ) ); ?> - you must have an old version of PHP.
    – user27457
    Mar 7, 2013 at 22:29

1 Answer 1

4

WordPress automatically serializes/unserializes the data when it's stored and retrieved, all you need to do is pass a php array as your data and you'll get the same array back when you get_post_meta.

$data = array(
    'label' => 'something',
    'desc' => 'someval',
    'id' => 'someval',
    'type' => 'someval'
);
update_post_meta( $post_id, 'your_key', $data );


$data = array(
    'field_1' => array(
        'label' => 'something',
        'desc' => 'someval',
        'id' => 'someval',
        'type' => 'someval'
    ),
    'field_2' => array(
        'label' => 'something',
        'desc' => 'someval',
        'id' => 'someval',
        'type' => 'someval'
    )
);
update_post_meta( $post_id, 'your_key', $data );
3
  • Thanks. So if I wanted to store meta field in an array, should I use a multidimensional array? For example, I want to store 'label', ''desc', 'id', 'type' & their values.
    – user28566
    Mar 8, 2013 at 20:43
  • you can save each field as a single dimensional array, or a multi-dimensional array of any number of levels, it's up to you and what makes sense for your data. I've edited the example above to hopefully clarify a bit. note that WordPress can store multiple entries under a single key as well. look at the examples in the post meta functions for more info and test them out.
    – Milo
    Mar 8, 2013 at 23:53
  • Thanks. I've been looking at this for an hour, so you've been a life saver for a newbie. Thanks, really appreciated!
    – user28566
    Mar 8, 2013 at 23:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.