admin管理员组

文章数量:1122832

I have a requirement to generate a rate calculator accessible to multiple users, each with their own set of criteria and values. I'm using user_meta fields to store the values for each user.

One element is a price threshold / rate pairing but each user may have a differing amount of thresholds so I can't simply fix a set amount of threshold / rate input fields. The user needs to be able to add these as required, one at a time.

eg.

[Property Price 1] / [Marketing Rate 1]

[ADD NEW RATE BUTTON]

[Property Price 2] / [Marketing Rate 2]

[ADD NEW RATE BUTTON]

[Property Price 3] / [Marketing Rate 3]

etc.

After clicking the [ADD NEW RATE BUTTON] it would need to generate a new custom user_meta pairing, numbered incrementally, so the above example would generate the following:

$property_price_1, $marketing_rate_1

$property_price_2, $marketing_rate_2

$property_price_3, $marketing_rate_3

etc.

I have it all working with fixed rate / threshold pairings, but I know the end users will have varying requirements, so don't want to limit them to eg. 10 rate / thresholds. Some may only have 2 or 3, others may have upwards of 20. Hence the need to be flexible with the amount.

I have a requirement to generate a rate calculator accessible to multiple users, each with their own set of criteria and values. I'm using user_meta fields to store the values for each user.

One element is a price threshold / rate pairing but each user may have a differing amount of thresholds so I can't simply fix a set amount of threshold / rate input fields. The user needs to be able to add these as required, one at a time.

eg.

[Property Price 1] / [Marketing Rate 1]

[ADD NEW RATE BUTTON]

[Property Price 2] / [Marketing Rate 2]

[ADD NEW RATE BUTTON]

[Property Price 3] / [Marketing Rate 3]

etc.

After clicking the [ADD NEW RATE BUTTON] it would need to generate a new custom user_meta pairing, numbered incrementally, so the above example would generate the following:

$property_price_1, $marketing_rate_1

$property_price_2, $marketing_rate_2

$property_price_3, $marketing_rate_3

etc.

I have it all working with fixed rate / threshold pairings, but I know the end users will have varying requirements, so don't want to limit them to eg. 10 rate / thresholds. Some may only have 2 or 3, others may have upwards of 20. Hence the need to be flexible with the amount.

Share Improve this question asked Aug 22, 2024 at 19:04 MussyMussy 1 1
  • Welcome to WPSE! To help us help you, please edit your question to include the code you'd like help with. Otherwise we'll all just be guessing. – Pat J Commented Aug 22, 2024 at 19:20
Add a comment  | 

1 Answer 1

Reset to default 1

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.

  1. 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>
  1. 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);
});
  1. 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();
}
  1. 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);
            }
        }
    });
});

本文标签: phpHow can I allow a user to add any number of custom usermeta fields on a WordPress frontend page