注册时的自定义用户字段
问题描述:
我正在为客户端创建自定义插件,我需要添加一些自定义用户字段。我已经搜遍了食典,但无法找到答案。注册时的自定义用户字段
我基本上需要添加一些新的行到MySQL中的用户表中,然后在注册过程中添加一些额外的字段。我确定有其他的插件允许你添加自定义的用户字段,但是我想直接将它加入到我的插件中。
我该怎么办?
答
我已经回答了类似的问题在WordPress的答案:Checkboxes in registration form。
您需要动作钩子register_form
(注入您的输入字段)和user_register
(处理它)。其余代码仅仅是示例代码,用于检查Profile和User Edit页面中的结果。
// REGISTRATION
add_action('register_form', 'signup_fields_wpse_87261');
add_action('user_register', 'handle_signup_wpse_87261', 10, 2);
// PROFILE
add_action('show_user_profile', 'user_field_wpse_87261');
add_action('personal_options_update', 'save_profile_fields_87261');
// USER EDIT
add_action('edit_user_profile', 'user_field_wpse_87261');
add_action('edit_user_profile_update', 'save_profile_fields_87261');
function signup_fields_wpse_87261() {
?>
<label>
<input type="checkbox" name="custom_feature_a" id="custom_feature_a" />
Enable feature A?
</label>
<br />
<label>
<input type="checkbox" name="custom_feature_b" id="custom_feature_b" />
Enable feature B?
</label>
<hr />
<?php
}
function handle_signup_wpse_87261($user_id, $data = null)
{
$feat_a = isset($_POST['custom_feature_a']) ? $_POST['custom_feature_a'] : false;
$feat_b = isset($_POST['custom_feature_b']) ? $_POST['custom_feature_b'] : false;
if ($feat_a)
{
add_user_meta($user_id, 'custom_feature_a', $feat_a);
}
if ($feat_b)
{
add_user_meta($user_id, 'custom_feature_b', $feat_b);
}
}
function user_field_wpse_87261($user)
{
$feat_a = get_user_meta($user->ID, 'custom_feature_a', true);
$feat_b = get_user_meta($user->ID, 'custom_feature_b', true);
?>
<h3><?php _e('Custom Fields'); ?></h3>
<table class="form-table">
<tr>
<td>
<label><?php
printf(
'<input type="checkbox" name="custom_feature_a" id="custom_feature_a" %1$s />',
checked($feat_a, 'on', false)
);
?>
<span class="description"><?php _e('Custom Feature A?'); ?></span>
</label>
</td>
</tr>
<tr>
<td>
<label><?php
printf(
'<input type="checkbox" name="custom_feature_b" id="custom_feature_b" %1$s />',
checked($feat_b, 'on', false)
);
?>
<span class="description"><?php _e('Custom Feature B?'); ?></span>
</label>
</td>
</tr>
</table>
<?php
}
function save_profile_fields_87261($user_id)
{
$feat_a = isset($_POST['custom_feature_a']) ? $_POST['custom_feature_a'] : false;
$feat_b = isset($_POST['custom_feature_b']) ? $_POST['custom_feature_b'] : false;
update_usermeta($user_id, 'custom_feature_a', $feat_a);
update_usermeta($user_id, 'custom_feature_b', $feat_b);
}
您使用的是默认还是自定义注册?不要触摸用户表,你需要'user_meta'。 – brasofilo 2013-04-04 21:14:48
现在默认注册。 – 2013-04-04 21:16:55