Create a page Meta Box listing all blog users

If someone wants to clean this up, all the better, but it gets the job done 🙂

If I understood you correctly, you need the ID for the user, yes?

For more info on $wp_user_query check out this post which was a partial resource for me writing this code: http://www.mattvarone.com/wordpress/list-users-with-wp_user_query/

// List Users
add_action("admin_init", "users_meta_init");

function users_meta_init(){
  add_meta_box("users-meta", "User Select", "users", "post", "normal", "high");
}

function users(){
  global $post;
  $custom = get_post_custom($post->ID);
  $users = $custom["users"][0];

    // prepare arguments
$user_args  = array(
// search only for Authors role
'role' => 'Author',
// order results by display_name
'orderby' => 'display_name'
);
// Create the WP_User_Query object
$wp_user_query = new WP_User_Query($user_args);
// Get the results
$authors = $wp_user_query->get_results();
// Check for results
if (!empty($authors))
{
    // Name is your custom field key
    echo "<select name="users">";
    // loop trough each author
    foreach ($authors as $author)
    {
        // get all the user's data
        $author_info = get_userdata($author->ID);
        $author_id = get_post_meta($post->ID, 'users', true);
        if($author_id == $author_info->ID) { $author_selected = 'selected="selected"'; } else { $author_selected = ''; }
        echo '<option value=".$author_info->ID." '.$author_selected.'>'.$author_info->first_name.' '.$author_info->last_name.'</option>';
    }
    echo "</select>";
} else {
    echo 'No authors found';
}

}

// Save Meta Details
add_action('save_post', 'save_userlist');

function save_userlist(){
  global $post;

if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
    return $post->ID;
}

  update_post_meta($post->ID, "users", $_POST["users"]);
}

Leave a Comment