Эти маршруты позволяют получить/создать/обновить/удалить всевозможные данные юзеров в WP.
А также с версии WP 5.6, появились маршруты которые позволяют получить/создать/обновить/удалить пароли приложений конкретного уюзера.
Возможные маршруты (конечные точки маршрутов описаны ниже):
/wp/v2/users // работает со всеми юзерами
/wp/v2/users/{ID} // работает с указанным юзером
/wp/v2/users/me // работает с текущим юзером
/wp/v2/users/{ID}/application-passwords // работает с указанным юзером
/wp/v2/users/me/application-passwords // работает с текущим юзером
/wp/v2/users/{ID}/application-passwords/uuid
/wp/v2/users/me/application-passwords/uuid
Схема
Схема показывает все поля, которые существуют для объекта: поля объекта которые вернет запрос.
Ресурс Users
Параметр
Контекст
Описание
id Число readonly
embed, view, edit
Уникальный идентификатор пользователя.
username Строка required
edit
Имя входа для пользователя.
name Строка
embed, view, edit
Отображаемое имя пользователя.
first_name Строка
edit
Имя пользователя.
last_name Строка
edit
Фамилия пользователя.
email Строка required
edit
Адрес email пользователя.
url Строка
embed, view, edit
URL пользователя.
description Строка
embed, view, edit
Описание пользователя.
link Строка readonly
embed, view, edit
URL автора для пользователя.
locale Строка
edit
Локаль для пользователя.
nickname Строка
edit
Ник пользователя.
slug Строка
embed, view, edit
Буквенно-цифровой идентификатор пользователя.
registered_date Строка readonly
edit
Дата регистрации пользователя.
roles Массив
edit
Роли назначенные пользователю.
password Строка required
Пароль пользователя (никогда не показывается).
capabilities Объект readonly
edit
Все возможности назначенные пользователю.
extra_capabilities Объект readonly
edit
Любые дополнительные возможности назначенные пользователю.
avatar_urls Объект readonly
embed, view, edit
URL аватара пользователя.
meta Объект
view, edit
Мета поля.
Ресурс Application Passwords
Параметр
Контекст
Описание
uuid Строка readonly
view, edit, embed
Уникальный идентификатор для пароля приложения.
app_id Строка
view, edit, embed
UUID предоставляемый приложением для уникальной идентификации. Рекомендуется использовать UUID v5 с пространством имен URL или DNS.
name Строка required
view, edit, embed
Название пароля приложения.
password Строка readonly
edit
Создаваемый пароль. Доступен после добавления приложения.
created Строка readonly
view, edit
Дата и время (GMT) создания пароля приложения.
last_used Строка/null readonly
view, edit
Дата и время (GMT) последнего использования пароля приложения.
last_ip Строка/null readonly
view, edit
IP-адрес, с которого последний раз использовался пароль приложения.
wp/v2/users
Запрос OPTIONS к маршруту вернет полное описание этого маршрута: эндпоинты их параметры, схему.
$ curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/users
GitHub
{
"namespace": "wp/v2",
"methods": [
"GET",
"POST"
],
"endpoints": [
{
"methods": [
"GET"
],
"args": {
"context": {
"description": "Рамки в которых сделан запрос, определяют поля в ответе.",
"type": "string",
"enum": [
"view",
"embed",
"edit"
],
"default": "view",
"required": false
},
"page": {
"description": "Текущая страница коллекции.",
"type": "integer",
"default": 1,
"minimum": 1,
"required": false
},
"per_page": {
"description": "Максимальное число объектов возвращаемое в выборке.",
"type": "integer",
"default": 10,
"minimum": 1,
"maximum": 100,
"required": false
},
"search": {
"description": "Ограничить результаты до совпадающих со строкой.",
"type": "string",
"required": false
},
"exclude": {
"description": "Убедиться что выборка исключает определенные ID.",
"type": "array",
"items": {
"type": "integer"
},
"default": [],
"required": false
},
"include": {
"description": "Ограничить выборку до определенных ID.",
"type": "array",
"items": {
"type": "integer"
},
"default": [],
"required": false
},
"offset": {
"description": "Сдвиг выборки на определенное число объектов.",
"type": "integer",
"required": false
},
"order": {
"default": "asc",
"description": "Упорядочить сортировку атрибута по возрастанию или убыванию.",
"enum": [
"asc",
"desc"
],
"type": "string",
"required": false
},
"orderby": {
"default": "name",
"description": "Сортировать коллекцию по атрибуту объекта.",
"enum": [
"id",
"include",
"name",
"registered_date",
"slug",
"include_slugs",
"email",
"url"
],
"type": "string",
"required": false
},
"slug": {
"description": "Ограничить выборку пользователями с одним или более специальными ярлыками.",
"type": "array",
"items": {
"type": "string"
},
"required": false
},
"roles": {
"description": "Ограничить выборку до пользователей удовлетворяющих как минимум одной указанной роли. Можно указать CSV список или одну роль.",
"type": "array",
"items": {
"type": "string"
},
"required": false
},
"who": {
"description": "Ограничить выборку пользователями-авторами.",
"type": "string",
"enum": [
"authors"
],
"required": false
}
}
},
{
"methods": [
"POST"
],
"args": {
"username": {
"description": "Имя входа для пользователя.",
"type": "string",
"required": true
},
"name": {
"description": "Отображаемое имя пользователя.",
"type": "string",
"required": false
},
"first_name": {
"description": "Имя пользователя.",
"type": "string",
"required": false
},
"last_name": {
"description": "Фамилия пользователя.",
"type": "string",
"required": false
},
"email": {
"description": "Адрес email пользователя.",
"type": "string",
"format": "email",
"required": true
},
"url": {
"description": "URL пользователя.",
"type": "string",
"format": "uri",
"required": false
},
"description": {
"description": "Описание пользователя.",
"type": "string",
"required": false
},
"locale": {
"description": "Локаль для пользователя.",
"type": "string",
"enum": [
"",
"en_US",
"ru_RU"
],
"required": false
},
"nickname": {
"description": "Ник пользователя.",
"type": "string",
"required": false
},
"slug": {
"description": "Буквенно-цифровой идентификатор пользователя.",
"type": "string",
"required": false
},
"roles": {
"description": "Роли назначенные пользователю.",
"type": "array",
"items": {
"type": "string"
},
"required": false
},
"password": {
"description": "Пароль пользователя (никогда не показывается).",
"type": "string",
"required": true
},
"meta": {
"description": "Мета поля.",
"type": "object",
"properties": [],
"required": false
}
}
}
],
"schema": {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "user",
"type": "object",
"properties": {
"id": {
"description": "Уникальный идентификатор пользователя.",
"type": "integer",
"context": [
"embed",
"view",
"edit"
],
"readonly": true
},
"username": {
"description": "Имя входа для пользователя.",
"type": "string",
"context": [
"edit"
],
"required": true
},
"name": {
"description": "Отображаемое имя пользователя.",
"type": "string",
"context": [
"embed",
"view",
"edit"
]
},
"first_name": {
"description": "Имя пользователя.",
"type": "string",
"context": [
"edit"
]
},
"last_name": {
"description": "Фамилия пользователя.",
"type": "string",
"context": [
"edit"
]
},
"email": {
"description": "Адрес email пользователя.",
"type": "string",
"format": "email",
"context": [
"edit"
],
"required": true
},
"url": {
"description": "URL пользователя.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
},
"description": {
"description": "Описание пользователя.",
"type": "string",
"context": [
"embed",
"view",
"edit"
]
},
"link": {
"description": "URL автора для пользователя.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
],
"readonly": true
},
"locale": {
"description": "Локаль для пользователя.",
"type": "string",
"enum": [
"",
"en_US",
"ru_RU"
],
"context": [
"edit"
]
},
"nickname": {
"description": "Ник пользователя.",
"type": "string",
"context": [
"edit"
]
},
"slug": {
"description": "Буквенно-цифровой идентификатор пользователя.",
"type": "string",
"context": [
"embed",
"view",
"edit"
]
},
"registered_date": {
"description": "Дата регистрации пользователя.",
"type": "string",
"format": "date-time",
"context": [
"edit"
],
"readonly": true
},
"roles": {
"description": "Роли назначенные пользователю.",
"type": "array",
"items": {
"type": "string"
},
"context": [
"edit"
]
},
"password": {
"description": "Пароль пользователя (никогда не показывается).",
"type": "string",
"context": [],
"required": true
},
"capabilities": {
"description": "Все возможности назначенные пользователю.",
"type": "object",
"context": [
"edit"
],
"readonly": true
},
"extra_capabilities": {
"description": "Любые дополнительные возможности назначенные пользователю.",
"type": "object",
"context": [
"edit"
],
"readonly": true
},
"avatar_urls": {
"description": "URL аватара пользователя.",
"type": "object",
"context": [
"embed",
"view",
"edit"
],
"readonly": true,
"properties": {
"24": {
"description": "URL аватары с размером изображения в 24 пикселей.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
},
"48": {
"description": "URL аватары с размером изображения в 48 пикселей.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
},
"96": {
"description": "URL аватары с размером изображения в 96 пикселей.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
}
}
},
"meta": {
"description": "Мета поля.",
"type": "object",
"context": [
"view",
"edit"
],
"properties": []
}
}
},
"_links": {
"self": [
{
"href": "https://wp-kama.ru/api/wp/v2/users"
}
]
}
}
Список юзеров
Алгоритм схож с работой функции get_users() .
Вид запроса
Доступ: публичный
GET /wp/v2/users
Параметры запроса
context(string)
Рамки в которых сделан запрос, определяют поля в ответе.
Может быть: view, embed, edit .
По умолчанию: view
page(integer)
Текущая страница коллекции.
По умолчанию: 1
per_page(integer)
Максимальное число объектов возвращаемое в выборке.
По умолчанию: 10
search(string)
Ограничить результаты до совпадающих со строкой.
exclude(array)
Исключить из выборки определенные ID. Указывается массив ID.
По умолчанию: []
include(array)
Ограничить выборку до определенных ID. Указывается массив ID.
По умолчанию: []
offset(integer)
Сдвиг выборки на определенное число объектов.
order(string)
Сортировать по возрастанию (asc) или убыванию (desc).
Может быть: asc, desc
По умолчанию: asc
orderby(string)
Поле по которому нужно сортировать коллекцию.
Может быть: id, include, name, registered_date, slug, include_slugs, email, url .
По умолчанию: name
slug(array)
Ярлык пользователя которого нужно получить. Можно указать несколько ярлыков в массиве.
roles(array)
Получить пользователй с указанной ролью. Можно указать несколько ролей в массиве. Можно указать CSV список или одну роль.
who(string)
Ограничить выборку пользователями-авторами.
Может быть: authors .
Пример запроса
$ curl http://demo.wp-api.org/wp-json/wp/v2/users?search=human
Ответ:
[
{
"id": 1,
"name": "Human Made",
"url": "",
"description": "",
"link": "https://demo.wp-api.org/author/humanmade/",
"slug": "humanmade",
"avatar_urls": {
"24": "http://2.gravatar.com/avatar/83888eb8aea456e4322577f96b4dbaab?s=24&d=mm&r=g",
"48": "http://2.gravatar.com/avatar/83888eb8aea456e4322577f96b4dbaab?s=48&d=mm&r=g",
"96": "http://2.gravatar.com/avatar/83888eb8aea456e4322577f96b4dbaab?s=96&d=mm&r=g"
},
"meta": [],
"_links": {
"self": [
{
"href": "https://demo.wp-api.org/wp-json/wp/v2/users/1"
}
],
"collection": [
{
"href": "https://demo.wp-api.org/wp-json/wp/v2/users"
}
]
}
},
{ ... }
]
Создание юзера
Алгоритм схож с работой функции wp_create_user() .
Вид запроса
Доступ: нужна авторизация
POST /wp/v2/users
Параметры запроса
username(строка) (обязательный)
Имя входа для пользователя.
email(строка) (обязательный)
Адрес e-mail пользователя.
password(строка) (обязательный)
Пароль пользователя (никогда не показывается).
name(строка)
Отображаемое имя пользователя.
first_name(строка)
Имя пользователя.
last_name(строка)
Фамилия пользователя.
url(строка)
URL пользователя.
description(строка)
Описание пользователя.
locale(строка)
Локаль для пользователя. Может быть: '', en_US, ru_RU, uk .
nickname(строка)
Ник пользователя.
slug(строка)
Буквенно-цифровой идентификатор пользователя.
roles(массив)
Роли назначенные пользователю. Указывается массив ролей.
meta(объект)
Мета поля.
Пример запроса
$ curl -X POST -i http://example.com/wp-json/wp/v2/users?username=neuser&email=asd@asd.ru&password=123456
Ответ:
{
"id": 2,
"username": "neuser",
"name": "neuser",
"first_name": "",
"last_name": "",
"email": "asd@asd.ru",
"url": "",
"description": "",
"link": "http://example.com/author/neuser/",
"locale": "ru_RU",
"nickname": "neuser",
"slug": "neuser",
"roles": [
"subscriber"
],
"registered_date": "2018-08-31T13:36:18+00:00",
"capabilities": {
"read": true,
"level_0": true,
"subscriber": true
},
"extra_capabilities": {
"subscriber": true
},
"avatar_urls": {
"24": "http://0.gravatar.com/avatar/3731f606afa8dccc9123bdd4062c4af1?s=24&d=mm&r=g",
"48": "http://0.gravatar.com/avatar/3731f606afa8dccc9123bdd4062c4af1?s=48&d=mm&r=g",
"96": "http://0.gravatar.com/avatar/3731f606afa8dccc9123bdd4062c4af1?s=96&d=mm&r=g"
},
"meta": [],
"_links": {
"self": [
{
"href": "http://example.com/wp-json/wp/v2/users/2"
}
],
"collection": [
{
"href": "http://example.com/wp-json/wp/v2/users"
}
]
}
}
Пример запроса на PHP c авторизацией
Авторизация работает на базе Паролей приложений
$res = wp_remote_post( 'https://wp-kama.dev/api/wp/v2/users', [
'headers' => [
'Authorization' => 'Basic a21RyBYVjJzIE5a2RVBWjQFtYTpg5W5uSTIYTRVIFUgeaw==',
],
'body' => [
'username' => 'testets2',
'email' => 'test@test.ts1',
'password' => 'test123',
],
] );
if( 200 === wp_remote_retrieve_response_code( $res ) ){
// успешно
}
else {
// ошибка
}
// out
print_r( json_decode( wp_remote_retrieve_body( $res ) ) );
В результате получим:
// Возможные ошибки при удачном запрос:
stdClass Object(
[code] => existing_user_login
[message] => Извините, это имя пользователя уже существует!
[data] =>
)
stdClass Object(
[code] => existing_user_email
[message] => Извините, этот адрес email уже используется!
[data] =>
)
// юзер создан
stdClass Object(
[id] => 4562
[username] => testets2
[name] => testets2
[first_name] =>
[last_name] =>
[email] => test@test.ts1
[url] =>
[description] =>
[link] => https://wp-kama.dev/id_author/testets2
[locale] => ru_RU
[nickname] =>
[slug] => testets2
[roles] => Array(
[0] => subscriber
)
[registered_date] => 2021-07-25T14:04:18+00:00
[capabilities] => stdClass Object(
[read] => 1
[level_0] => 1
[subscriber] => 1
)
[extra_capabilities] => stdClass Object(
[subscriber] => 1
)
[avatar_urls] => stdClass Object(
[24] => https://secure.gravatar.com/avatar/2c0ba19f07a7894f544290488963e835?s=24&d=mystery&r=g
[48] => https://secure.gravatar.com/avatar/2c0ba19f07a7894f544290488963e835?s=48&d=mystery&r=g
[96] => https://secure.gravatar.com/avatar/2c0ba19f07a7894f544290488963e835?s=96&d=mystery&r=g
)
[meta] => Array()
[_links] => stdClass Object(
[self] => Array(
[0] => stdClass Object(
[href] => https://wp-kama.dev/api/wp/v2/users/4562
)
)
[collection] => Array(
[0] => stdClass Object(
[href] => https://wp-kama.dev/api/wp/v2/users
)
)
)
)
wp/v2/users/{ID}
Запрос OPTIONS к маршруту вернет полное описание этого маршрута: эндпоинты их параметры, схему.
$ curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/users/{ID}
GitHub
{
"namespace": "wp/v2",
"methods": [
"GET",
"POST",
"PUT",
"PATCH",
"DELETE"
],
"endpoints": [
{
"methods": [
"GET"
],
"args": {
"id": {
"required": false,
"description": "Уникальный идентификатор пользователя.",
"type": "integer"
},
"context": {
"required": false,
"default": "view",
"enum": [
"view",
"embed",
"edit"
],
"description": "Рамки в которых сделан запрос, определяют поля в ответе.",
"type": "string"
}
}
},
{
"methods": [
"POST",
"PUT",
"PATCH"
],
"args": {
"id": {
"required": false,
"description": "Уникальный идентификатор пользователя.",
"type": "integer"
},
"username": {
"required": false,
"description": "Имя входа для пользователя.",
"type": "string"
},
"name": {
"required": false,
"description": "Отображаемое имя пользователя.",
"type": "string"
},
"first_name": {
"required": false,
"description": "Имя пользователя.",
"type": "string"
},
"last_name": {
"required": false,
"description": "Фамилия пользователя.",
"type": "string"
},
"email": {
"required": false,
"description": "Адрес e-mail пользователя.",
"type": "string"
},
"url": {
"required": false,
"description": "URL пользователя.",
"type": "string"
},
"description": {
"required": false,
"description": "Описание пользователя.",
"type": "string"
},
"locale": {
"required": false,
"enum": [
"",
"en_US",
"ru_RU",
"uk"
],
"description": "Локаль для пользователя.",
"type": "string"
},
"nickname": {
"required": false,
"description": "Ник пользователя.",
"type": "string"
},
"slug": {
"required": false,
"description": "Буквенно-цифровой идентификатор пользователя.",
"type": "string"
},
"roles": {
"required": false,
"description": "Роли назначенные пользователю.",
"type": "array",
"items": {
"type": "string"
}
},
"password": {
"required": false,
"description": "Пароль пользователя (никогда не показывается).",
"type": "string"
},
"meta": {
"required": false,
"description": "Мета поля.",
"type": "object"
}
}
},
{
"methods": [
"DELETE"
],
"args": {
"id": {
"required": false,
"description": "Уникальный идентификатор пользователя.",
"type": "integer"
},
"force": {
"required": false,
"default": false,
"description": "Должно быть истинным, так как пользователей нельзя переместить в корзину.",
"type": "boolean"
},
"reassign": {
"required": true,
"description": "Переназначить удаленные записи пользователя и ссылки на этот ID пользователя.",
"type": "integer"
}
}
}
],
"schema": {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "user",
"type": "object",
"properties": {
"id": {
"description": "Уникальный идентификатор пользователя.",
"type": "integer",
"context": [
"embed",
"view",
"edit"
],
"readonly": true
},
"username": {
"description": "Имя входа для пользователя.",
"type": "string",
"context": [
"edit"
],
"required": true
},
"name": {
"description": "Отображаемое имя пользователя.",
"type": "string",
"context": [
"embed",
"view",
"edit"
]
},
"first_name": {
"description": "Имя пользователя.",
"type": "string",
"context": [
"edit"
]
},
"last_name": {
"description": "Фамилия пользователя.",
"type": "string",
"context": [
"edit"
]
},
"email": {
"description": "Адрес e-mail пользователя.",
"type": "string",
"format": "email",
"context": [
"edit"
],
"required": true
},
"url": {
"description": "URL пользователя.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
},
"description": {
"description": "Описание пользователя.",
"type": "string",
"context": [
"embed",
"view",
"edit"
]
},
"link": {
"description": "URL автора для пользователя.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
],
"readonly": true
},
"locale": {
"description": "Локаль для пользователя.",
"type": "string",
"enum": [
"",
"en_US",
"ru_RU",
"uk"
],
"context": [
"edit"
]
},
"nickname": {
"description": "Ник пользователя.",
"type": "string",
"context": [
"edit"
]
},
"slug": {
"description": "Буквенно-цифровой идентификатор пользователя.",
"type": "string",
"context": [
"embed",
"view",
"edit"
]
},
"registered_date": {
"description": "Дата регистрации пользователя.",
"type": "string",
"format": "date-time",
"context": [
"edit"
],
"readonly": true
},
"roles": {
"description": "Роли назначенные пользователю.",
"type": "array",
"items": {
"type": "string"
},
"context": [
"edit"
]
},
"password": {
"description": "Пароль пользователя (никогда не показывается).",
"type": "string",
"context": [],
"required": true
},
"capabilities": {
"description": "Все возможности назначенные пользователю.",
"type": "object",
"context": [
"edit"
],
"readonly": true
},
"extra_capabilities": {
"description": "Любые дополнительные возможности назначенные пользователю.",
"type": "object",
"context": [
"edit"
],
"readonly": true
},
"avatar_urls": {
"description": "URL аватара пользователя.",
"type": "object",
"context": [
"embed",
"view",
"edit"
],
"readonly": true,
"properties": {
"24": {
"description": "URL аватары с размером изображения в 24 пикселей.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
},
"48": {
"description": "URL аватары с размером изображения в 48 пикселей.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
},
"96": {
"description": "URL аватары с размером изображения в 96 пикселей.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
}
}
},
"meta": {
"description": "Мета поля.",
"type": "object",
"context": [
"view",
"edit"
],
"properties": []
}
}
}
}
Получение юзера
Алгоритм схож с работой функции get_userdata() .
Вид запроса
Доступ: публичный
GET /wp/v2/users/{id}
Параметры запроса
context(строка)
Область, в которой выполняется запрос; определяет поля, присутствующие в ответе.
Может быть: view, embed, edit
По умолчанию: view
Пример запроса
$ curl http://demo.wp-api.org/wp-json/wp/v2/users/1
{
"id": 1,
"name": "Human Made",
"url": "",
"description": "",
"link": "https://demo.wp-api.org/author/humanmade/",
"slug": "humanmade",
"avatar_urls": {
"24": "http://2.gravatar.com/avatar/83888eb8aea456e4322577f96b4dbaab?s=24&d=mm&r=g",
"48": "http://2.gravatar.com/avatar/83888eb8aea456e4322577f96b4dbaab?s=48&d=mm&r=g",
"96": "http://2.gravatar.com/avatar/83888eb8aea456e4322577f96b4dbaab?s=96&d=mm&r=g"
},
"meta": [],
"_links": {
"self": [
{
"href": "https://demo.wp-api.org/wp-json/wp/v2/users/1"
}
],
"collection": [
{
"href": "https://demo.wp-api.org/wp-json/wp/v2/users"
}
]
}
}
Обновление юзера
Алгоритм схож с работой функции wp_update_user() .
Вид запроса
Доступ: нужна авторизация
POST|PUT|PATCH /wp/v2/users/{id}
Параметры запроса
username(строка)
Имя входа для пользователя.
name(строка)
Отображаемое имя пользователя.
first_name(строка)
Имя пользователя.
last_name(строка)
Фамилия пользователя.
email(строка)
Адрес e-mail пользователя.
url(строка)
URL пользователя на страницу постов.
description(строка)
Описание пользователя.
locale(строка)
Локаль для пользователя. Может быть: '', en_US, ru_RU, uk .
nickname(строка)
Ник пользователя.
slug(строка)
Ярлык пользователя.
roles(массив)
Роли назначенные пользователю. Массив строк.
password(строка)
Пароль пользователя (никогда не показывается).
meta(объект)
Мета поля.
Пример запроса
$ curl -X POST http://demo.wp-api.org/wp-json/wp/v2/users/2?email=foo@bar.com
Удаление юзера
Алгоритм схож с работой функции wp_delete_user() .
Вид запроса
Доступ: нужна авторизация
DELETE /wp/v2/users/{id}
Параметры запроса
force(true/false)
Всегда должно быть true, так как пользователей нельзя переместить в корзину.
По умолчанию: false
reassign(число) (обязательный)
ID пользователя на которого нужно перекинуть все посты и ссылки, удаляемого пользователя. Если не указать этот параметр, то все посты удаляемого пользователя будут также удалены.
Пример запроса
$ curl -X DELETE http://demo.wp-api.org/wp-json/wp/v2/users/2
Ошибка: не указан параметр reassign
{
"code": "rest_missing_callback_param",
"message": "Отсутствует параметр: reassign",
"data": {
"status": 400,
"params": [
"reassign"
]
}
}
Укажем этот параметр:
$ curl -X DELETE http://demo.wp-api.org/wp-json/wp/v2/users/2?reassign=1
Опять ошибка: нужно обязательно указать force=true
{
"code": "rest_trash_not_supported",
"message": "Пользователей нельзя переместить в корзину. Установите 'force=true' для удаления.",
"data": {
"status": 501
}
}
Укажем и этот параметр
$ curl -X DELETE http://demo.wp-api.org/wp-json/wp/v2/users/2?reassign=1&force=true
Юзер удален:
{
"deleted": true,
"previous": {
"id": 2,
"username": "neuser",
"name": "neuser",
"first_name": "",
"last_name": "",
"email": "asd@asd.ru",
"url": "",
"description": "",
"link": "http://example.com/author/neuser/",
"locale": "ru_RU",
"nickname": "neuser",
"slug": "neuser",
"roles": [
"subscriber"
],
"registered_date": "2018-08-31T13:36:18+00:00",
"capabilities": {
"read": true,
"level_0": true,
"subscriber": true
},
"extra_capabilities": {
"subscriber": true
},
"avatar_urls": {
"24": "http://0.gravatar.com/avatar/3731f606afa8dccc9123bdd4062c4af1?s=24&d=mm&r=g",
"48": "http://0.gravatar.com/avatar/3731f606afa8dccc9123bdd4062c4af1?s=48&d=mm&r=g",
"96": "http://0.gravatar.com/avatar/3731f606afa8dccc9123bdd4062c4af1?s=96&d=mm&r=g"
},
"meta": []
}
}
wp/v2/users/me
Маршрут требует авторизацию в REST.
Запрос OPTIONS к маршруту вернет полное описание этого маршрута: эндпоинты их параметры, схему.
$ curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/users/me
GitHub
{
"namespace": "wp/v2",
"methods": [
"GET",
"POST",
"PUT",
"PATCH",
"DELETE"
],
"endpoints": [
{
"methods": [
"GET"
],
"args": {
"context": {
"required": false,
"default": "view",
"enum": [
"view",
"embed",
"edit"
],
"description": "Scope under which the request is made; determines fields present in response.",
"type": "string"
}
}
},
{
"methods": [
"POST",
"PUT",
"PATCH"
],
"args": {
"username": {
"required": false,
"description": "Login name for the user.",
"type": "string"
},
"name": {
"required": false,
"description": "Display name for the user.",
"type": "string"
},
"first_name": {
"required": false,
"description": "First name for the user.",
"type": "string"
},
"last_name": {
"required": false,
"description": "Last name for the user.",
"type": "string"
},
"email": {
"required": false,
"description": "The email address for the user.",
"type": "string"
},
"url": {
"required": false,
"description": "URL of the user.",
"type": "string"
},
"description": {
"required": false,
"description": "Description of the user.",
"type": "string"
},
"locale": {
"required": false,
"enum": [
"",
"en_US"
],
"description": "Locale for the user.",
"type": "string"
},
"nickname": {
"required": false,
"description": "The nickname for the user.",
"type": "string"
},
"slug": {
"required": false,
"description": "An alphanumeric identifier for the user.",
"type": "string"
},
"roles": {
"required": false,
"description": "Roles assigned to the user.",
"type": "array",
"items": {
"type": "string"
}
},
"password": {
"required": false,
"description": "Password for the user (never included).",
"type": "string"
},
"meta": {
"required": false,
"description": "Meta fields.",
"type": "object"
}
}
},
{
"methods": [
"DELETE"
],
"args": {
"force": {
"required": false,
"default": false,
"description": "Required to be true, as users do not support trashing.",
"type": "boolean"
},
"reassign": {
"required": true,
"description": "Reassign the deleted user's posts and links to this user ID.",
"type": "integer"
}
}
}
],
"schema": {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "user",
"type": "object",
"properties": {
"id": {
"description": "Unique identifier for the user.",
"type": "integer",
"context": [
"embed",
"view",
"edit"
],
"readonly": true
},
"username": {
"description": "Login name for the user.",
"type": "string",
"context": [
"edit"
],
"required": true
},
"name": {
"description": "Display name for the user.",
"type": "string",
"context": [
"embed",
"view",
"edit"
]
},
"first_name": {
"description": "First name for the user.",
"type": "string",
"context": [
"edit"
]
},
"last_name": {
"description": "Last name for the user.",
"type": "string",
"context": [
"edit"
]
},
"email": {
"description": "The email address for the user.",
"type": "string",
"format": "email",
"context": [
"edit"
],
"required": true
},
"url": {
"description": "URL of the user.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
},
"description": {
"description": "Description of the user.",
"type": "string",
"context": [
"embed",
"view",
"edit"
]
},
"link": {
"description": "Author URL of the user.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
],
"readonly": true
},
"locale": {
"description": "Locale for the user.",
"type": "string",
"enum": [
"",
"en_US"
],
"context": [
"edit"
]
},
"nickname": {
"description": "The nickname for the user.",
"type": "string",
"context": [
"edit"
]
},
"slug": {
"description": "An alphanumeric identifier for the user.",
"type": "string",
"context": [
"embed",
"view",
"edit"
]
},
"registered_date": {
"description": "Registration date for the user.",
"type": "string",
"format": "date-time",
"context": [
"edit"
],
"readonly": true
},
"roles": {
"description": "Roles assigned to the user.",
"type": "array",
"items": {
"type": "string"
},
"context": [
"edit"
]
},
"password": {
"description": "Password for the user (never included).",
"type": "string",
"context": [],
"required": true
},
"capabilities": {
"description": "All capabilities assigned to the user.",
"type": "object",
"context": [
"edit"
],
"readonly": true
},
"extra_capabilities": {
"description": "Any extra capabilities assigned to the user.",
"type": "object",
"context": [
"edit"
],
"readonly": true
},
"avatar_urls": {
"description": "Avatar URLs for the user.",
"type": "object",
"context": [
"embed",
"view",
"edit"
],
"readonly": true,
"properties": {
"24": {
"description": "Avatar URL with image size of 24 pixels.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
},
"48": {
"description": "Avatar URL with image size of 48 pixels.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
},
"96": {
"description": "Avatar URL with image size of 96 pixels.",
"type": "string",
"format": "uri",
"context": [
"embed",
"view",
"edit"
]
}
}
},
"meta": {
"description": "Meta fields.",
"type": "object",
"context": [
"view",
"edit"
],
"properties": []
}
}
},
"_links": {
"self": "https://demo.wp-api.org/wp-json/wp/v2/users/me"
}
}
Получение текущего юзера
Маршрут работает также как предыдущий wp/v2/users/{ID}
.
$ curl http://example.com/wp-json/wp/v2/users/me
{
"id": 1,
"name": "kama",
"url": "",
"description": "",
"link": "http://example.com/author/kama/",
"slug": "kama",
"avatar_urls": {
"24": "http://1.gravatar.com/avatar/155e695ab2251ee3c482c1e3e690683b?s=24&d=mm&r=g",
"48": "http://1.gravatar.com/avatar/155e695ab2251ee3c482c1e3e690683b?s=48&d=mm&r=g",
"96": "http://1.gravatar.com/avatar/155e695ab2251ee3c482c1e3e690683b?s=96&d=mm&r=g"
},
"meta": [],
"_links": {
"self": [
{
"href": "http://example.com/wp-json/wp/v2/users/1"
}
],
"collection": [
{
"href": "http://example.com/wp-json/wp/v2/users"
}
]
}
}
Обновление текущего юзера
См. маршрут wp/v2/users/{ID}
.
Удаление текущего юзера
См. маршрут wp/v2/users/{ID}
.
/wp/v2/users/{ID}/application-passwords
/wp/v2/users/me/application-passwords
Запрос OPTIONS к маршруту вернет полное описание этого маршрута.
OPTIONS http://demo.wp-api.org/wp-json/wp/v2/users/{ID}/application-passwords
GitHub
{
"namespace": "wp/v2",
"methods": [
"GET",
"POST",
"DELETE"
],
"endpoints": [
{
"methods": [
"GET"
],
"args": {
"context": {
"description": "Рамки в которых сделан запрос, определяют поля в ответе.",
"type": "string",
"enum": [
"view",
"embed",
"edit"
],
"default": "view",
"required": false
}
}
},
{
"methods": [
"POST"
],
"args": {
"app_id": {
"description": "UUID предоставляемый приложением для уникальной идентификации. Рекомендуется использовать UUID v5 с пространством имен URL или DNS.",
"type": "string",
"format": "uuid",
"required": false
},
"name": {
"description": "Название пароля приложения.",
"type": "string",
"required": true
}
}
},
{
"methods": [
"DELETE"
],
"args": []
}
],
"schema": { ... }
}
Просмотр Паролей приложений юзера
Получает все пароли приложения пользователя. См. WP_Application_Passwords::get_user_application_passwords() .
Вид запроса
GET /wp/v2/users/{id}/application-passwords
Параметры запроса
$context(строка)
Рамки в которых сделан запрос, определяют поля в ответе. Возможные значения: view
, embed
, edit
.
По умолчанию: view
Пример запроса
GET https://wp-kama.ru/api/wp/v2/users/1/application-passwords
Ответ:
[
{
"uuid": "e76548d7-0274-438c-b04a-904301bda4d32",
"app_id": "",
"name": "Тест",
"created": "2020-12-23T13:47:55",
"last_used": "2020-12-23T13:48:55",
"last_ip": "89.149.201.210",
"_links": {
"self": [
{
"href": "https://wp-kama.ru/api/wp/v2/users/1/application-passwords/e76548d7-0274-438c-b04a-904301bda4d32"
}
]
}
},
{
"uuid": "e76548d7-0274-438c-b04a-987301bda4d32",
"app_id": "",
"name": "Test2",
"created": "2020-12-23T13:49:08",
"last_used": null,
"last_ip": null,
"_links": {
"self": [
{
"href": "https://wp-kama.ru/api/wp/v2/users/1/application-passwords/e76548d7-0274-438c-b04a-987301bda4d32"
}
]
}
}
]
Создание Пароля приложения
Создает пароль приложения. См. WP_Application_Passwords::create_new_application_password() .
Вид запроса
Доступ: требует авторизацию.
POST /wp/v2/users/{id}/application-passwords
Параметры запроса
$name(строка) (обязательный)
Название пароля приложения.
$app_id(строка)
UUID предоставляемый приложением для уникальной идентификации. Рекомендуется использовать UUID v5 с пространством имен URL или DNS.
По умолчанию: ''
Пример запроса
POST https://wp-kama.ru/api/wp/v2/users/1/application-passwords?name=Test2
Ответ:
{
"uuid": "c9e5ce07-0ccb-4a2e-963a-feda93cf8bab",
"app_id": "",
"name": "Test2",
"created": "2020-12-23T12:41:38",
"last_used": null,
"last_ip": null,
"password": "pNFX LyvZ gz75 tiks UZiT xlSL",
"_links": {
"self": [
{
"href": "https://wp-kama.ru/api/wp/v2/users/1/application-passwords/c9e5ce07-0ccb-4a2e-963a-feda93cf8bab"
}
]
}
}
Удаление Паролей приложения юзера
Удаляет все пароли предложений пользователя. См. WP_Application_Passwords::delete_all_application_passwords() .
Вид запроса
Доступ: требует авторизацию.
DELETE /wp-json/wp/v2/users/1/application-passwords
Параметры запроса
Параметров нет.
/wp/v2/users/{ID}/application-passwords/uuid
/wp/v2/users/me/application-passwords/uuid
Эти эндпоинты такие же как предыдущие, только работают с конкретным паролем приложения.
Запрос OPTIONS к маршруту вернет полное описание этого маршрута.
OPTIONS http://demo.wp-api.org/wp-json/wp/v2/users/{ID}/application-passwords/{uuid}
GitHub
{
"namespace": "wp/v2",
"methods": [
"GET",
"POST",
"PUT",
"PATCH",
"DELETE"
],
"endpoints": [
{
"methods": [
"GET"
],
"args": {
"context": {
"description": "Рамки в которых сделан запрос, определяют поля в ответе.",
"type": "string",
"enum": [
"view",
"embed",
"edit"
],
"default": "view",
"required": false
}
}
},
{
"methods": [
"POST",
"PUT",
"PATCH"
],
"args": {
"app_id": {
"description": "UUID предоставляемый приложением для уникальной идентификации. Рекомендуется использовать UUID v5 с пространством имен URL или DNS.",
"type": "string",
"format": "uuid",
"required": false
},
"name": {
"description": "Название пароля приложения.",
"type": "string",
"required": false
}
}
},
{
"methods": [
"DELETE"
],
"args": []
}
],
"schema": { ... }
}
Просмотр Пароля приложения
Аналогично запросу GET /wp/v2/users/{ID}/application-passwords .
Вид запроса
GET /wp/v2/users/{ID}/application-passwords/{uuid}
Пример
GET https://example.com/wp-json/wp/v2/users/1/application-passwords/e79943d8-0367-287c-b07a-90001bda4d32
Ответ:
{
"uuid": "e79943d8-0367-287c-b07a-90001bda4d32",
"app_id": "",
"name": "Test2",
"created": "2020-12-23T13:49:08",
"last_used": null,
"last_ip": null,
"_links": {
"self": [
{
"href": "https://example.com/api/wp/v2/users/1/application-passwords/e79943d8-0367-287c-b07a-90001bda4d32"
}
]
}
}
Добавление Пароля приложения
Аналогично запросу POST /wp/v2/users/{ID}/application-passwords .
Вид запроса
POST|PUT|PATCH /wp/v2/users/{ID}/application-passwords/{uuid}
Пример
POST https://example.com/wp-json/wp/v2/users/1/application-passwords/e77743d8-0367-287c-b07a-90001bda4d32
Удаление Пароля приложения
Аналогично запросу DELETE /wp/v2/users/{ID}/application-passwords .
Вид запроса
DELETE /wp/v2/users/{ID}/application-passwords/{uuid}
Пример
DELETE https://example.com/wp-json/wp/v2/users/1/application-passwords/e78743d8-0367-287c-b07a-90001bda4d32