Wordpress的功能有问题update_user_meta()
我正在尝试为用户更新或添加一个新的自定义元值,用户已经在编辑配置文件中使用了自定义元。但是当我做这个函数的时候update_user_meta()
外部edit-profile.php
, 只是对我不起作用。
我有一个类似联系人页面的页面,表单将在其中编辑个人资料的自定义元数据,在wordpress的正面,就像wordpress的普通页面一样,但当他提交表单时,他只是不更新,以下是我的代码:
用户提交时:
function update_termini() {
$user = wp_get_current_user();
$userData = array();
$userData[\'checkbox\'] = intval( $_POST[\'custom_user_fields_checkbox\'] );
update_user_meta( $user, \'custom_user_fields\', $userData );
}
add_action(\'edit_user_profile\', \'update_termini\');
最合适的回答,由SO网友:Aamer Shahzad 整理而成
wp_get_current_user()
返回一个对象。update_user_meta( $user_id, $meta_key, $meta_value, $prev_value
) 接受user_id
作为第一个参数。使用以下代码从中获取用户IDwp_get_current_user()
update_user_meta( $user->ID, \'custom_user_fields\', $userData );
SO网友:nyedidikeke
这是更新用户元的正确方法,这样您就不会弄乱数据;对代码段进行了注释,以提供更多详细信息:
function update_termini( $user_id ) {
// print_r( $user_id );
// exit;
// $user_id holds the user ID of the actual user\'s profile page subjected to the edit.
// That is the right way to do it.
// The comment block right below this very block is an ineffective way as it will only work
// for a current user editing his/her own profile page and why it is not the best way out;
// Using wp_get_current_user() to derive at a user ID as in: $user = wp_get_current_user();
// then, $user->ID; will enable you get the user ID of the CURRENT USER and that is going
// to AFFECT YOUR DATA NEGATIVELY when an administrator for instance edits the profile of
// a user; what will happen then is that the data of the custom field will actually update
// the records of the administrator rather than that of the intended user whos profile in
// being edited by the administrator.
// You can then perform any checks if needed,
if ( current_user_can( \'edit_user\' ) ) {
// print_r( $_POST );
// exit;
// And proceed to update the user meta of the actual user\'s profile page subjected to the edit;
// it may or may not be the current user.
// This way, you are sure to update the right field with right information.
// For the purpose of this update, it is assumed the name of our newly added custom field
// is custom_user_fields_checkbox.
update_user_meta( $user_id, \'custom_user_fields_checkbox\', $_POST[\'custom_user_fields_checkbox\'] );
}
}
add_action( \'edit_user_profile\', \'update_termini\' );