0

I have input fields with names like: child1, child[2], child[3] and so on. A user can add as many fields as he wants, its handled with jquery and dynamically ads an input field with [n] in the end of the name.

Now I need to store this data to database in WordPress plugin I work on. And later retrieve this data to display it on the website, and of cause add those field out fields in admin page, where user edits data.

I know how to store one field for example child to the database in WordPress, it would be something like that:

<?php $child = get_post_meta( $post->ID, 'child', true ); ?>

<?php
function save_child_data( $post_id ) {

  // Check if exists
  if(! isset($_POST['child'])){return;}

  // Sanitize
  $child_data = sanitize_text_field( $_POST['child'] );

  // Store data
  update_post_meta( $post_id, 'child', $child_data);

}
add_action( 'save_post', 'save_child_data' );
?>

<!-- Field in admin -->
<input type="text" name="child" id="child" value="<?php echo esc_attr($child); ?>">

<!-- Front office -->
<div>Child: <?php echo get_post_meta( $post->ID, 'child', true ); ?></div>

So my question is how do I handle this array like child[n]?

Or another question maybe it is better to just use child1, child2, child3 and handle it as regular input fields?

So you understand what I mean by dynamically added block here is a jsfiddle link: http://jsfiddle.net/alexchizhov/LC2K6/

1
  • Use serialization (i suggest json) and store it all in one field Commented Jul 31, 2014 at 11:31

1 Answer 1

2

Store it as an JSON or serialized string in one field.

https://www.php.net/manual/en/function.json-encode.php

https://www.php.net/manual/en/function.serialize.php

Sign up to request clarification or add additional context in comments.

5 Comments

will i be able to separate this data later to retrieve it one value by one?
Yes. With json_decode() or unserialize() you can get the array back and fetch them one by one with any loop (foreach() for example).
How should I use it with update_post_meta in wordpress?
Well, you can just throw the json or serialized string in there. update_post_meta( $post_id, 'child', serialize($child_data)); codex.wordpress.org/Function_Reference/update_post_meta
Actually, forget that with serialize(). update_post_meta already does that if you pass an array. You just have to unserialize it back to an array. codex.wordpress.org/Function_Reference/get_post_meta

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.