从前端更新用户元数据


Update user meta from frontend

我的wordpress站点有如下表单:

<?php
  $current_user = wp_get_current_user();  
 ?>
<div class="rh_contact_form">    
    <div class="mdl-textfield rhc_phone_number_class">  
        <?php if ( is_user_logged_in() ) { ?>
            <?php echo '<input type="text" id="rhc_phone" name="rhc_phone" placeholder="Phone number" value="' .$current_user -> rh_phone. '"/>' ;?>
        <?php }else{ ?>
            <input class="mdl-textfield__input" type="text" id="rhc_phone" name="rhc_phone" placeholder="Phone number" value=""/>
         <?php } ?>                                             
    </div>
    <div class="rhc_ask">   
        <textarea class="mdl-textfield__input" type="text" rows= "3" id="rhc_ask" name="rhc_ask" placeholder="Ask seller"></textarea>           
    </div>  
    <input type="submit">Submit</input>
</div>

所以,有两个用户metakeys: rh_phonerh_ask

如何更新这两个的元值?

谢谢!

您需要在表单处理函数中添加类似的内容。也可以在该函数中调用"当前用户",或者通过表单中的隐藏字段传递ID。

$current_user = wp_get_current_user();
$rh_phone = sanitize_text_field($_POST['rh_phone']);
$rh_ask= sanitize_text_field($_POST['rh_ask']);
if( isset($rh_phone) ){
    update_post_meta($current_user, 'rh_phone', $rh_phone);
}
if( isset($rh_ask) ){
    update_post_meta($current_user, 'rh_ask', $rh_ask);
}

你可以在这里找到更多关于update_post_meta()的信息:https://codex.wordpress.org/Function_Reference/update_post_meta。