Add to array dynamically, WordPress

I have a form where a user can edit prices for their own small company. I have 2 predefined pricefield coming from an array – What I don’t quite know how to do and need a little help with is that the user should be able to add their own prices aswell… So when the user clicks the input with class “btn-addprice” – a new row is added with the same two inputfields (I’ll do this this with JS)… So user should be able to add a name and a price…

But when adding the fields, what should the name of the inputs be for this to work, and furthermore, how do I add this to my prices array when saving ? Somehow the users input in the 2 fields needs to be added to the same kind of array, and added to be databases, so it looks like my current price array??

Ahh, as you can here, im a bit lost 🙂

The thing im doing now when saving is just saving the price array:

//Update prices
    update_user_meta($current_user->ID, 'prices', $_POST['prices']);

The rest of my code looks like regarding the prices looks like:

    $get_prices = array();
    $get_prices = get_user_meta($userid->ID, 'prices', true);

    $prices = array(
        'first' => esc_html__('1. Konsultation','findbehandler'),
        'followup'  => esc_html__('Opfølgende behandling','findbehandler'),

<div class="box box--white">
    <p>Indtast jeres priser i hele kroner. F.eks 400
    <div class="prices row">
        <div id="prices"></div>
            if( isset( $prices ) && !empty( $prices ) ) {
            foreach( $prices as $key => $value )    {

                $price_db   = isset( $get_prices[$key] ) ? $get_prices[$key] : '';

            <div class="col-md-2">
                <label><?php echo esc_attr( $value );?></label>
            <div class="col-md-8">
                <input type="text" name="prices[<?php echo esc_attr( $key );?>]" value="<?php echo esc_attr( $price_db );?>" placeholder="<?php esc_html_e('Indtast pris','findbehandler');?>">
            <div class="col-md-2">
                <div class="input-group-btn">
                    <button class="btn btn-addprice" type="button" onclick="addprice();"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> </button>
        <?php }}?>

Read more here: Add to array dynamically, WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *