Wordpress: Create a new usermeta field for users

会有一股神秘感。 提交于 2019-12-03 03:31:31

You can create a simple plugin to hook into the user profile actions and add a new field.

To add the field to the form you can hook into the show_user_profile and edit_user_profile actions and output the form field HTML. The below uses a checkbox rather than a drop-down.

add_action('show_user_profile', 'my_user_profile_edit_action');
add_action('edit_user_profile', 'my_user_profile_edit_action');
function my_user_profile_edit_action($user) {
  $checked = (isset($user->artwork_approved) && $user->artwork_approved) ? ' checked="checked"' : '';
?>
  <h3>Other</h3>
  <label for="artwork_approved">
    <input name="artwork_approved" type="checkbox" id="artwork_approved" value="1"<?php echo $checked; ?>>
    Artwork approved
  </label>
<?php 
}

Then you need to hook into the personal_options_update and edit_user_profile_update actions, get the value of your field and save this as user meta.

add_action('personal_options_update', 'my_user_profile_update_action');
add_action('edit_user_profile_update', 'my_user_profile_update_action');
function my_user_profile_update_action($user_id) {
  update_user_meta($user_id, 'artwork_approved', isset($_POST['artwork_approved']));
}

Your condition would then be as below.

if (get_user_meta($current_user->ID, 'artwork_approved', true)) {

Shouldn't the second block of code read:

add_action('personal_options_update', 'my_user_profile_update_action');
add_action('edit_user_profile_update', 'my_user_profile_update_action');
function my_user_profile_update_action($user_id) {
  update_user_meta($user_id, 'artwork_approved', $_POST['artwork_approved']);
}

The value saved by update_user_meta is $_POST['artwork_approved'] not isset($_POST['artwork_approved']).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!