# Users

# Users

A _User_ is an access account with corresponding capabilities within the WordPress installation. Each WordPress user has, at the bare minimum, a username, password and email address.

Once a user account is created, that user may log in using the WordPress Admin (or programmatically) to access WordPress functions and data. WordPress stores the Users in the `users` table.

## Roles and Capabilities

Users are assigned [roles](https://developer.wordpress.org/plugins/users/roles-and-capabilities/#roles), and each role has a set of [capabilities](https://developer.wordpress.org/plugins/users/roles-and-capabilities/#capabilities).

You can create new roles with their own set of capabilities. Custom capabilities can also be created and assigned to existing roles or new roles.

In WordPress, developers can take advantage of user roles to limit the set of actions an account can perform.

## The Principle of Least Privileges

WordPress adheres to the principal of least privileges, the practice of giving a user _only_ the privileges that are essential for performing the desired work. You should follow this lead when possible by creating roles where appropriate and checking capabilities before performing sensitive tasks.

# Roles and Capabilities

Roles and capabilities are two important aspects of WordPress that allow you to control user privileges.

WordPress stores the Roles and their Capabilities in the `options` table under the `user_roles` key.

## Roles

A role defines a set of capabilities for a user. For example, what the user may see and do in his dashboard.

**By default, WordPress have six roles:**

- Super Admin
- Administrator
- Editor
- Author
- Contributor
- Subscriber

More roles can be added and the default roles can be removed.

![Users roles](https://i3.wp.com/developer.wordpress.org/files/2014/09/wp-roles.png)

### Adding Roles

Add new roles and assign capabilities to them with [`add_role()`](https://developer.wordpress.org/reference/functions/add_role/).

```
function wporg_simple_role() {
  add_role(
    'simple_role',
    'Simple Role',
    array(
      'read'         => true,
      'edit_posts'   => true,
      'upload_files' => true,
    ),
  );
}

// Add the simple_role.
add_action( 'init', 'wporg_simple_role' );
```

[alert]After the first call to [`add_role()`](https://developer.wordpress.org/reference/functions/add_role/), the Role and it's Capabilities will be stored in the database!

Sequential calls will do nothing: including altering the capabilities list, which might not be the behavior that you're expecting.[/alert]

[info]To alter the capabilities list in bulk: remove the role using [`remove_role()`](https://developer.wordpress.org/reference/functions/remove_role/) and add it again using [`add_role()`](https://developer.wordpress.org/reference/functions/add_role/) with the new capabilities.

Make sure to do it only if the capabilities differ from what you're expecting (i.e. condition this) or you'll degrade performance considerably![/info]

### Removing Roles

Remove roles with [`remove_role()`](https://developer.wordpress.org/reference/functions/remove_role/).

```
function wporg_simple_role_remove() {
  remove_role( 'simple_role' );
}

// Remove the simple_role.
add_action( 'init', 'wporg_simple_role_remove' );
```

[alert]After the first call to [`remove_role()`](https://developer.wordpress.org/reference/functions/remove_role/), the Role and it's Capabilities will be removed from the database!

Sequential calls will do nothing.[/alert]

[info]If you're removing the default roles:

- We advise **against** removing the Administrator and Super Admin roles!
- Make sure to keep the code in your plugin/theme as future WordPress updates may add these roles again.
- Run `update_option('default_role', YOUR_NEW_DEFAULT_ROLE)` since you'll be deleting `subscriber` which is WP's default role.[/info]

## Capabilities

Capabilities define what a **role** can and can not do: edit posts, publish posts, etc.

[info]Custom post types can require a certain set of Capabilities.[/info]

### Adding Capabilities

You may define new capabilities for a role.

Use [`get_role()`](https://developer.wordpress.org/reference/functions/get_role/) to get the role object, then use the `add_cap()` method of that object to add a new capability.

```
function wporg_simple_role_caps() {
  // Gets the simple_role role object.
  $role = get_role( 'simple_role' );

  // Add a new capability.
  $role->add_cap( 'edit_others_posts', true );
}

// Add simple_role capabilities, priority must be after the initial role definition.
add_action( 'init', 'wporg_simple_role_caps', 11 );
```

[info]It's possible to add custom capabilities to any role.

Under the default WordPress admin, they would have no effect, but they can be used for custom admin screen and front-end areas.[/info]

### Removing Capabilities

You may remove capabilities from a role.

The implementation is similar to Adding Capabilities with the difference being the use of `remove_cap()` method for the role object.

## Using Roles and Capabilities

### Get Role

Get the role object including all of it's capabilities with [`get_role()`](https://developer.wordpress.org/reference/functions/get_role/).

### User Can

Check if a user have a specified **role** or **capability** with [`user_can()`](https://developer.wordpress.org/reference/functions/user_can/).

```
user_can( $user, $capability );
```

[warning]There is an undocumented, third argument, $args, that may include the object against which the test should be performed.

E.g. Pass a post ID to test for the capability of that specific post.[/warning]

### Current User Can

[`current_user_can()`](https://developer.wordpress.org/reference/functions/current_user_can/) is a wrapper function for [`user_can()`](https://developer.wordpress.org/reference/functions/user_can/) using the current user object as the `$user` parameter.

Use this in scenarios where back-end and front-end areas should require a certain level of privileges to access and/or modify.

```
current_user_can( $capability );
```

### Example

Here's a practical example of adding an Edit link on the in a template file if the user has the proper capability:

```
if ( current_user_can( 'edit_posts' ) ) {
  edit_post_link( esc_html__( 'Edit', 'wporg' ), '<p>', '</p>' );
}
```

## Multisite

The [`current_user_can_for_blog()`](https://developer.wordpress.org/reference/functions/current_user_can_for_blog/) function is used to test if the current user has a certain **role** or **capability** on a specific blog.

```
current_user_can_for_blog( $blog_id, $capability );
```

## Reference

Codex Reference for [User Roles and Capabilities](https://wordpress.org/documentation/article/roles-and-capabilities/).

# Working with User Metadata

## Introduction

WordPress' `users` table was designed to contain only the essential information about the user.

[info]As of WP 4.7 the table contains: `ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status` and `display_name`.[/info]

Because of this, to store additional data, the `usermeta` table was introduced, which can store any arbitrary amount of data about a user.

Both tables are tied together using one-to-many relationship based on the `ID` in the `users` table.

## Manipulating User Metadata

There are two main ways for manipulating User Metadata.

1. A form field in the user's profile screen.
2. Programmatically, via a function call.

### via a Form Field

The form field option is suitable for cases where the user will have access to the WordPress admin area, in which he will be able to view and edit profiles.

Before we dive into an example, it's important to understand the hooks involved in the process and why they are there.

#### `show_user_profile` hook

This action hook is fired whenever a user edits **it's own** user profile.

**Remember,** a user that doesn't have the capability of editing his own profile won't fire this hook.

#### `edit_user_profile` hook

This action hook is fired whenever a user edits a user profile of **somebody else**.

**Remember,** a user that doesn't have the capability for editing 3rd party profiles won't fire this hook.

#### Example Form Field

In the example below we will be adding a birthday field to the all profile screens. Saving it to the database on profile updates.

```
/**
 * The field on the editing screens.
 *
 * @param $user WP_User user object
 */
function wporg_usermeta_form_field_birthday( $user ) {
  ?>
  <h3>It's Your Birthday</h3>
  <table class="form-table">
    <tr>
      <th>
        <label for="birthday">Birthday</label>
      </th>
      <td>
        <input type="date"
          class="regular-text ltr"
          id="birthday"
          name="birthday"
          value="<?= esc_attr( get_user_meta( $user->ID, 'birthday', true ) ) ?>"
          title="Please use YYYY-MM-DD as the date format."
          pattern="(19[0-9][0-9]|20[0-9][0-9])-(1[0-2]|0[1-9])-(3[01]|[21][0-9]|0[1-9])"
          required>
        <p class="description">
          Please enter your birthday date.
        </p>
      </td>
    </tr>
  </table>
  <?php
}

/**
 * The save action.
 *
 * @param $user_id int the ID of the current user.
 *
 * @return bool Meta ID if the key didn't exist, true on successful update, false on failure.
 */
function wporg_usermeta_form_field_birthday_update( $user_id ) {
  // check that the current user have the capability to edit the $user_id
  if ( ! current_user_can( 'edit_user', $user_id ) ) {
    return false;
  }

  // create/update user meta for the $user_id
  return update_user_meta(
    $user_id,
    'birthday',
    $_POST['birthday']
  );
}

// Add the field to user's own profile editing screen.
add_action(
  'show_user_profile',
  'wporg_usermeta_form_field_birthday'
);

// Add the field to user profile editing screen.
add_action(
  'edit_user_profile',
  'wporg_usermeta_form_field_birthday'
);

// Add the save action to user's own profile editing screen update.
add_action(
  'personal_options_update',
  'wporg_usermeta_form_field_birthday_update'
);

// Add the save action to user profile editing screen update.
add_action(
  'edit_user_profile_update',
  'wporg_usermeta_form_field_birthday_update'
);
```

### Programmatically

This option is suitable for cases where you're building a custom user area and/or plan to disable access to the WordPress admin area.

The functions available for manipulating User Metadata are: [`add_user_meta()`](https://developer.wordpress.org/reference/functions/add_user_meta/), [`update_user_meta()`](https://developer.wordpress.org/reference/functions/update_user_meta/), [`delete_user_meta()`](https://developer.wordpress.org/reference/functions/delete_user_meta/) and [`get_user_meta()`](https://developer.wordpress.org/reference/functions/get_user_meta/).

#### Add

```
add_user_meta(
  int $user_id,
  string $meta_key,
  mixed $meta_value,
  bool $unique = false
);
```

Please refer to the Function Reference about [`add_user_meta()`](https://developer.wordpress.org/reference/functions/add_user_meta/) for full explanation about the used parameters.

#### Update

```
update_user_meta(
  int $user_id,
  string $meta_key,
  mixed $meta_value,
  mixed $prev_value = ''
);
```

Please refer to the Function Reference about [`update_user_meta()`](https://developer.wordpress.org/reference/functions/update_user_meta/) for full explanation about the used parameters.

#### Delete

```
delete_user_meta(
  int $user_id,
  string $meta_key,
  mixed $meta_value = ''
);
```

Please refer to the Function Reference about [`delete_user_meta()`](https://developer.wordpress.org/reference/functions/delete_user_meta/) for full explanation about the used parameters.

#### Get

```
get_user_meta(
  int $user_id,
  string $key = '',
  bool $single = false
);
```

Please refer to the Function Reference about [`get_user_meta()`](https://developer.wordpress.org/reference/functions/get_user_meta/) for full explanation about the used parameters.

Please note, if you pass only the `$user_id`, the function will retrieve all Metadata as an associative array.

You can render User Metadata anywhere in your plugin or theme.

# Working with Users

## Adding Users

To add a user you can use `wp_create_user()` or `wp_insert_user()`.

`wp_create_user()` creates a user using only the username, password and email parameters while `wp_insert_user()` accepts an array or object describing the user and its properties.

### Create User

`wp_create_user()` allows you to create a new WordPress user.

[info]It uses [`wp_slash()`](https://developer.wordpress.org/reference/functions/wp_slash/) to escape the values. The PHP compact() function to create an array with these values. The [`wp_insert_user()`](https://developer.wordpress.org/reference/functions/wp_insert_user/) to perform the insert operation.[/info]

Please refer to the Function Reference about `wp_create_user()` for full explanation about the used parameters.

#### Example Create

```
// check if the username is taken
$user_id = username_exists( $user_name );

// check that the email address does not belong to a registered user
if ( ! $user_id && email_exists( $user_email ) === false ) {
  // create a random password
  $random_password = wp_generate_password( 12, false );
  // create the user
  $user_id = wp_create_user(
    $user_name,
    $random_password,
    $user_email
  );
}
```

## Insert User

```
wp_insert_user( $userdata );
```

[info]The function calls a filter for most predefined properties.

The function performs the action `user_register` when creating a user (user ID does not exist).

The function performs the action `profile_update` when updating the user (user ID exists).[/info]

Please refer to the Function Reference about `wp_insert_user()` for full explanation about the used parameters.

### Example Insert

Below is an example showing how to insert a new user with the website profile field filled in.

```
$username  = $_POST['username'];
$password  = $_POST['password'];
$website   = $_POST['website'];
$user_data = [
  'user_login' => $username,
  'user_pass'  => $password,
  'user_url'   => $website,
];

$user_id = wp_insert_user( $user_data );

// success
if ( ! is_wp_error( $user_id ) ) {
  echo 'User created: ' . $user_id;
}
```

## Updating Users

`wp_update_user()` Updates a single user in the database. The update data is passed along in the `$userdata` array/object.

To update a single piece of user meta data, use `update_user_meta()` instead. To create a new user, use `wp_insert_user()` instead.

[info]If current user's password is being updated, then the cookies will be cleared![/info]

Please refer to the Function Reference about `wp_update_user()` for full explanation about the used parameters.

### Example Update

Below is an example showing how to update a user's website profile field.

```
$user_id = 1;
$website = 'https://wordpress.org';

$user_id = wp_update_user(
  array(
    'ID'       => $user_id,
    'user_url' => $website,
  )
);

if ( is_wp_error( $user_id ) ) {
  // error
} else {
  // success
}
```

## Deleting Users

`wp_delete_user()` deletes the user and optionally reassign associated entities to another user ID.

[info]The function performs the action `deleted_user` after the user have been deleted.[/info]

[alert]If the `$reassign` parameter is not set to a valid user ID, then all entities belonging to the deleted user will be deleted![/alert]

Please refer to the Function Reference about `wp_delete_user()` for full explanation about the used parameters.