Updating user post meta

时间:2015-09-30 23:15:12

标签: php wordpress meta

So I have a very basic form which allows users to edit their profile data:

<?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>

Now, how do I implement wp_update_user in this case to update the user meta only if value is different from the current value or if it is not empty (for example, if they delete the current value in the input field, then it does not get rid of the meta).

Any help will be much appreciated.

1 个答案:

答案 0 :(得分:1)

简单的答案是你应该像这样实施支票:

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())..