I’ve set up my user profiles to allow custom taxonomies following this tutorial.

Ideally, I’d like to use the default Tag meta box from the Post screen, so users can easily add new terms and find commonly used ones. I’m currently using a checkbox list, but this could get very long as we’ll have a number of taxonomies. Could I somehow use the post_tags_meta_box()? I’ve looked into add_meta_box() but that doesn’t work on 'user'.

3 s
3

This code works for me. It uses ‘locations’ custom taxonomy and ‘suggest’ javascript. You need to extend it to support multiple term selection.

Add custom field to user-edit screen and store metadata when user/admin updates profile

// for account owner
add_action('show_user_profile', 'add_custom_user_profile_fields');
add_action('personal_options_update', 'save_custom_user_profile_fields');

// for admins
add_action('edit_user_profile', 'add_custom_user_profile_fields');
add_action('edit_user_profile_update', 'save_custom_user_profile_fields');

function add_custom_user_profile_fields($user) {
    printf(
    '
<h3>%1$s</h3>
<table class="form-table">
<tr>
<th><label for="location">%2$s</label></th>
<td>
  <input type="text" name="location" id="location" value="%3$s" class="regular-text" />
  <br /><span class="description">%4$s</span>
</td>
</tr>
</table>
',      __('Extra Profile Information', 'locale'),
        __('Location', 'locale'),
        esc_attr(get_user_meta($user->ID, 'location', true)),
        __('Start typing location name.', 'locale')
    );
}

function save_custom_user_profile_fields($user_id) {
    if (!current_user_can('edit_user', $user_id))
        return FALSE;

    $location_name = ( isset($_POST['location']) ) ? $_POST['location'] : '';

    // use your taxonomy name instead of 'locations'
    $location = get_term_by('name', $location_name, 'locations');

    // human readable value and id
    update_user_meta($user_id, 'location', $location_name);
    update_user_meta($user_id, 'location_id', $location->term_id);
}

Enqueue suggest javascript for user-edit screen only (assuming you use this in custom theme)

function admin_scripts($hook) {
    $screen = get_current_screen();
    if ('user-edit' == $screen->id) {
    wp_enqueue_script(
        'user-edit-tag',
        get_stylesheet_directory_uri() . '/js/usermeta.js',
        array('suggest'),
        '20140509',
        true
    );
    }
}

usermeta.js

jQuery(document).ready(function($) {
   // use 'tax=your_taxonomy_name' instead of 'tax=locations'
   $('#location').suggest(ajaxurl+"?action=ajax-tag-search&tax=locations",{
        multiple:false,
        multipleSep: ","
    });
});

Leave a Reply

Your email address will not be published. Required fields are marked *