更新用户 post 元数据

Updating user post meta

所以我有一个非常基本的表单,允许用户编辑他们的个人资料数据:

<?php
$current_user = wp_get_current_user();
?>
<div class="rh_contact_form">       
    <?php echo '<input type="text" id="rhc_phone" name="rhc_phone" placeholder="Phone number" value="' .$current_user -> billing_phone. '"/>' ;?>
    <?php echo '<input type="text" id="rhc_question" name="rhc_question" placeholder="My question" value="' .$current_user -> my_question. '"/>' ;?>
    <div class="rh_button">         
        <button type="button">
            <i class="icons">done</i>
        </button>
    </div> 
</div>

现在,在这种情况下,我如何实现 wp_update_user 以仅在值与当前值不同或不为空时更新用户元数据(例如,如果他们删除当前值输入字段,那么它不会摆脱元)。

任何帮助将不胜感激。

简单的答案是您应该像这样实施检查:

if ( get_user_meta($user_id,  'some_meta_key', true ) != $new_value ){
// old data is different from new data 
}

现在,它还没有经过我的彻底测试,但我相信您需要将它包装在一个函数中并像这样过滤 update_user_metadata 操作:

首先添加过滤器。

add_filter( 'update_user_metadata', 'pre_update_check_meta', 10, 5 );

然后函数

function pre_update_check_meta( $null, $object_id, $meta_key, $meta_value, $prev_value ) {

if ( 'some_meta_key' == $meta_key && empty( $meta_value ) ) {
        // Now check for NULL or EMPTY or compare with $old_value or whatever you want
        return true; // this means: stop saving the value into the database
    }

    return null; // this means: go on with the normal execution in meta.php

}

您只需要按照说明使用过滤器,并将 update_user_meta() 操作添加到您的操作中(我相信您称之为 svf_send_message() )..