'Wordpress update_user_meta is not working

I want to build a function for my wordpress page which behaves as follows:

  1. If a specific user meta value exists, it is printed
  2. If it doesn't exist, an input field allows the user to add it

My code is posted below, when I try to execute it a few weird things happen:

  1. When the user submits the form, the page reloads but the input field is still there, i.e. the new meta value isn't printed
  2. If I manually refresh the page the meta value is now printed (and also exists in the database)
  3. If I manually refresh again the input field returns again (and the meta value is deleted from the database)

So for some reason resubmitting the page deletes the meta value? What have I done wrong?

<?php 

$custom_value = get_user_meta( get_current_user_id(), 'custom_value', true );

if ( $custom_value ) { 
   echo $custom_value;
} else { ?>
   <form action="" method="post" style="display: flex;">
      <input type="text" name="c_val" id="c_val" />
      <button type="submit" value="">Add</button>
   </form>
   <?php 
      if ( isset( $_POST['c_val'] ) ) {
         $c_val = $_POST['c_val'];
         update_user_meta( get_current_user_id(), 'custom_value', $c_val );
      }
} 

?>


Solution 1:[1]

When your user clicks submit on your form, their browser POSTs to your page. That means WordPress's code to render the page, code that includes your example code, runs again from scratch, but this time with values in the $_POST array.

So your logic to determine whether your form has been posted needs to check that array before you retrieve the meta value.

<?php 
/* did the user post a new custom value ? */
if ( isset( $_POST['c_val'] ) {
  $custom_value = sanitize_text_field( $_POST['c_val'] );
  update_user_meta( get_current_user_id(), 'custom_value', $custom_value );
} else {
  $custom_value = get_user_meta( get_current_user_id(), 'custom_value', true );
}
if ( $custom_value ) { 
   /* if we have a custom value, use it. */
   echo esc_html($custom_value);
} else { ?>
   <form action="" method="post" style="display: flex;">
      <input type="text" name="c_val" id="c_val" />
      <button type="submit" value="">Add</button>
   </form>
}
?>

I added some code to clean up the text coming in from the user.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 O. Jones