To allow users to add any number of custom user_meta
fields on a WordPress front-end page, you can approach this by using JavaScript for dynamic form generation and then handle the form submission with PHP to store the values in user_meta
. Here’s how you can achieve this.
- Create the Front-end Form
First, create the HTML form with a template for the price/rate pairs and a button to add more pairs
<form id="rate-calculator-form"> <div id="rate-fields"> <div class="rate-field"> <input type="text" name="property_price_1" placeholder="Property Price 1"> <input type="text" name="marketing_rate_1" placeholder="Marketing Rate 1"> </div> </div> <button type="button" id="add-rate">Add New Rate</button> <button type="submit">Submit</button> </form>
- Add JavaScript for Dynamic Fields
Use JavaScript to add more fields when the “Add New Rate” button is clicked:
let rateCounter = 1; document.getElementById('add-rate').addEventListener('click', function() { rateCounter++; const newRateField = document.createElement('div'); newRateField.classList.add('rate-field'); newRateField.innerHTML = ` `; document.getElementById('rate-fields').appendChild(newRateField); });
- Handle Form Submission in PHP
When the form is submitted, loop through the posted data and save each pair as a custom user_meta field:
add_action('wp_ajax_save_user_meta', 'save_user_meta'); add_action('wp_ajax_nopriv_save_user_meta', 'save_user_meta'); function save_user_meta() { $user_id = get_current_user_id(); if ($user_id && !empty($_POST)) { $i = 1; while (isset($_POST["property_price_{$i}"]) && isset($_POST["marketing_rate_{$i}"])) { $property_price = sanitize_text_field($_POST["property_price_{$i}"]); $marketing_rate = sanitize_text_field($_POST["marketing_rate_{$i}"]); update_user_meta($user_id, "property_price_{$i}", $property_price); update_user_meta($user_id, "marketing_rate_{$i}", $marketing_rate); $i++; } wp_send_json_success('Data saved successfully!'); } else { wp_send_json_error('Unable to save data.'); } wp_die(); }
- Submit the Form with AJAX
Finally, submit the form using AJAX to prevent page reloads and handle the response:
jQuery('#rate-calculator-form').on('submit', function(e) { e.preventDefault(); jQuery.ajax({ type: 'POST', url: ajaxurl, data: jQuery(this).serialize(), success: function(response) { if (response.success) { alert(response.data); } else { alert('Error: ' + response.data); } } }); });