admin管理员组文章数量:1434380
Why am I not allowed to update existing user-meta fields when hooking on to edit_user_profile_update
hook? I use this code
add_action( 'edit_user_profile_update', 'xpl_registration_save' );
function xpl_registration_save( $user_id ) {
$user = get_userdata($user_id);
$user->add_role( 'gardner' );
update_user_meta($user_id,'last_name','Smith');
update_user_meta($user_id,'dogs_name','Sam');
}
This works for the last field, dogs_name
, which is added, and updated. But for core fields, some other fields which have been created by another plugin, it doesn't work. How come?
Why am I not allowed to update existing user-meta fields when hooking on to edit_user_profile_update
hook? I use this code
add_action( 'edit_user_profile_update', 'xpl_registration_save' );
function xpl_registration_save( $user_id ) {
$user = get_userdata($user_id);
$user->add_role( 'gardner' );
update_user_meta($user_id,'last_name','Smith');
update_user_meta($user_id,'dogs_name','Sam');
}
This works for the last field, dogs_name
, which is added, and updated. But for core fields, some other fields which have been created by another plugin, it doesn't work. How come?
1 Answer
Reset to default 0You can't change some user meta fields using edit_user_profile_update
hook,
because it is triggered before processing data from the form. So, you save user's meta to database, then edit form is processed and WP overrides your values. This hook is triggered after each profile edit.
You should use insert_user_meta
filter (available since WP v4.4) to change or add user's meta.
Filter is applied after user is created/updated, but meta has not yet been saved to the DB.
add_action( 'insert_user_meta', 'se329613_insert_user_meta', 30, 3);
/**
* @param array $meta {
* Default meta values and keys for the user.
*
* @type string $nickname
* @type string $first_name
* @type string $last_name
* @type string $description
* @type bool $rich_editing
* @type bool $syntax_highlighting
* @type bool $comment_shortcuts
* @type string $admin_color
* @type int|bool $use_ssl
* @type bool $show_admin_bar_front
* }
* @param WP_User $user
* @param bool $update
*/
function se329613_insert_user_meta( $meta, $user, $update )
{
// set only when adding a new user
if ( !$update ) {
$meta['last_name'] = 'Smith';
$meta['dogs_name'] = 'Sam';
}
return $meta;
}
You can use the user_register
action to perform other operations. Functions hooked to user_register
are executed when everything is already saved.
add_action( 'user_register' , 'se329613_user_register' );
function se329613_user_register( $user_id )
{
/* some code */
}
本文标签: user metaExisting usermeta fields not updated
版权声明:本文标题:user meta - Existing user_meta fields not updated 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745628031a2667094.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论