How to save data of an input field to an array

I’m writing a plugin to edit my profile page.

How can I save data of an input field to the database and then display it?

Read More

This is my code. The first part is the display in HTML:

<form method ="POST">
    <div id= 'dynamic_input_groups'>
        <input type='text' name='group[]' id='group[]' class="regular-text"
            value="<?php echo esc_attr( get_the_author_meta( 'group', $user->ID ) ); ?>" />

        <input type="button" class="button-primary" value="Add"
            onClick="addInput('dynamic_input_groups');">
    </div>
</form>

And the second part is the script for the button click and the input field:

<script>
var counter = 1;
var limit = 15;
function addInput(divName) {
    if (counter == limit) {
        alert("You have reached the limit of adding " + counter + " inputs");
    } else {
        var newdiv = document.createElement('div');
        newdiv.innerHTML = " <br><input type='text' name='group[]'' class='regular-text'>";
        document.getElementById(divName).appendChild(newdiv);
        counter++;
    }
}
</script>

And the final part saves the data to the database:

update_usermeta( $user_id, 'group', $_POST['group'] );

Related posts

Leave a Reply

1 comment

  1. Don’t use update_usermeta, it is deprecated, update_user_meta is the one to use.

    You get the previously saved value out with get_user_meta.

    <input type='text' name='group[]' id='group[]' class="regular-text"
        value="<?php echo esc_attr( get_user_meta( $user->ID, 'group', true ) ); ?>" />