Answer the question
In order to leave comments, you need to log in
Why does not update the user's metadata through the form on the site?
I'm trying to make a form so site users can add/update their meta fields. At first glance, everything seems to work, but when you try to refresh the page, the field value remains empty and nothing is written to the database. What am I doing wrong?
Form code:
<?php
function update_basic_user_meta() {
global $current_user;
$communication_email = get_user_meta( $current_user->ID, 'communication_email', true );
?>
<form action="" method="POST" class="">
<input type="text" id="communicationEmail" name="communication_email" class="" value="<?php echo $communication_email; ?>">
<button class="" type="submit">Сохранять</button>
</form>
<?php
$communication_email = sanitize_text_field($_POST['communication_email'])
update_user_meta( $current_user->ID, 'communication_email', $communication_email );
}
update_basic_user_meta();
?>
Answer the question
In order to leave comments, you need to log in
1. update_user_meta does not work because in the line above there is an error - there is no end-of-line character (semicolon)
2. According to your logic, the update occurs after the form is displayed on the screen. (update_user_meta after form tag). which means that if the meta is initially empty, then the field will be empty. so that the data appears, you need to refresh the page after making changes, but you have a problem from the first paragraph. If the meta is not initially empty, then after submitting new data, the old value will be displayed until you refresh the page .... it's better to process the data before the form tag
function update_basic_user_meta(){
global $current_user;
$communication_meta=!empty($_POST['communication_email'])?$_POST['communication_email']:'';
if(!empty($communication_meta)){update_user_meta($current_user->ID,'communication_email',sanitize_text_field($communication_meta));}
$communication_email=get_user_meta($current_user->ID,'communication_email',true);?>
<form action="" method="POST" class="">
<input type="text" id="communicationEmail" name="communication_email" class="" value="<?php echo !empty($communication_email)?$communication_email:''; ?>">
<button class="" type="submit">Сохранять</button>
</form><?php }
update_basic_user_meta();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question