phpwordpressmetadataelementorusermetadata

Wordpress how to calculate a value for a user and update related custom meta field


I have created a front-end form on Wordpress using Elementor Pro, and it is successfully updating the user meta of the logged in user when submitted.

I would now like to calculate a separate custom meta field, using the values that were submitted in the form.

In other words: when a user submits a value for custom field straight_speed, I would like to automatically calculate the straight_speed_percent using the value just entered, and save it against the user.

For now, the calculation for straight_speed_percent can just be straight_speed multiplied by 100.

(The custom field for straight_speed_percent has already been created).

Initially a value will need to be added for straight_speed_percent, but if the form is resubmitted and straight_speed is changed, I would like the value to be updated.

I have tried the following code, but it doesn't seem to be working. Any help would be greatly appreciated!

$current_user = wp_get_current_user();
$current_user->ID;

$straight_speed = get_user_meta ('straight_speed', $current_user);

$straight_acceleration_percent_value  = $straight_speed * '100';

update_user_meta( $current_user, 'straight_acceleration_percent', '$straight_acceleration_percent_value' );

Solution

  • There are some syntax and logical errors in your code!

    Use the following snippet:

    $current_user = wp_get_current_user();
    
    $straight_speed = get_user_meta($current_user->ID, 'straight_speed', true);
    
    if ($straight_speed) {
    
      $straight_acceleration_percent_value  = (int)$straight_speed * 100;
    
      update_user_meta($current_user->ID, 'straight_speed_percent', $straight_acceleration_percent_value);
    
    } 
    

    This answer has been tested and works fine! Let me know if it works for you too!